8322 nl: misleading-indentation
[unleashed/tickless.git] / usr / src / cmd / cmd-inet / usr.lib / mdnsd / uds_daemon.c
blob9af68dc95d894e8b2dab9484d115904dfb8c1e37
1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2015 Apple Inc. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
30 #include <stdlib.h>
31 #include <stdio.h>
33 #include "mDNSEmbeddedAPI.h"
34 #include "DNSCommon.h"
35 #include "uDNS.h"
36 #include "uds_daemon.h"
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;
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
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
60 #if APPLE_OSX_mDNSResponder
61 #include <WebFilterDNS/WebFilterDNS.h>
63 #if !NO_WCF
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));
69 // Do we really need to define a macro for "if"?
70 #define CHECK_WCF_FUNCTION(X) if (X)
71 #endif // ! NO_WCF
73 #else
74 #define NO_WCF 1
75 #endif // APPLE_OSX_mDNSResponder
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)
81 #define MAX_ANONYMOUS_DATA 256
83 // ***************************************************************************
84 #if COMPILER_LIKES_PRAGMA_MARK
85 #pragma mark -
86 #pragma mark - Types and Data Structures
87 #endif
89 typedef enum
91 t_uninitialized,
92 t_morecoming,
93 t_complete,
94 t_error,
95 t_terminated
96 } transfer_state;
98 typedef struct request_state request_state;
100 typedef void (*req_termination_fn)(request_state *request);
102 typedef struct registered_record_entry
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;
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
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;
129 // for multi-domain default browsing
130 typedef struct browser_t
132 struct browser_t *next;
133 domainname domain;
134 DNSQuestion q;
135 } browser_t;
137 #ifdef _WIN32
138 typedef unsigned int pid_t;
139 typedef unsigned int socklen_t;
140 #endif
142 struct request_state
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;
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
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 mDNSu32 interfaceIndex;
176 union
178 registered_record_entry *reg_recs; // list of registrations for a connection-oriented request
179 struct
181 mDNSInterfaceID interface_id;
182 mDNSBool default_domain;
183 mDNSBool ForceMCast;
184 domainname regtype;
185 browser_t *browsers;
186 const mDNSu8 *AnonData;
187 } browser;
188 struct
190 mDNSInterfaceID InterfaceID;
191 mDNSu16 txtlen;
192 void *txtdata;
193 mDNSIPPort port;
194 domainlabel name;
195 char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
196 domainname type;
197 mDNSBool default_domain;
198 domainname host;
199 mDNSBool autoname; // Set if this name is tied to the Computer Name
200 mDNSBool autorename; // Set if this client wants us to automatically rename on conflict
201 mDNSBool allowremotequery; // Respond to unicast queries from outside the local link?
202 int num_subtypes;
203 mDNSBool AnonData;
204 service_instance *instances;
205 } servicereg;
206 struct
208 mDNSInterfaceID interface_id;
209 mDNSu32 flags;
210 mDNSu32 protocol;
211 DNSQuestion q4;
212 DNSQuestion *q42;
213 DNSQuestion q6;
214 DNSQuestion *q62;
215 mDNSu8 v4ans;
216 mDNSu8 v6ans;
217 } addrinfo;
218 struct
220 mDNSIPPort ReqExt; // External port we originally requested, for logging purposes
221 NATTraversalInfo NATinfo;
222 } pm;
223 struct
225 DNSServiceFlags flags;
226 DNSQuestion q_all;
227 DNSQuestion q_default;
228 } enumeration;
229 struct
231 DNSQuestion q;
232 DNSQuestion *q2;
233 mDNSu8 ans;
234 } queryrecord;
235 struct
237 DNSQuestion qtxt;
238 DNSQuestion qsrv;
239 const ResourceRecord *txt;
240 const ResourceRecord *srv;
241 mDNSs32 ReportTime;
242 mDNSBool external_advertise;
243 } resolve;
244 } u;
247 // struct physically sits between ipc message header and call-specific fields in the message buffer
248 typedef struct
250 DNSServiceFlags flags; // Note: This field is in NETWORK byte order
251 mDNSu32 ifi; // Note: This field is in NETWORK byte order
252 DNSServiceErrorType error; // Note: This field is in NETWORK byte order
253 } reply_hdr;
255 typedef struct reply_state
257 struct reply_state *next; // If there are multiple unsent replies
258 mDNSu32 totallen;
259 mDNSu32 nwriten;
260 ipc_msg_hdr mhdr[1];
261 reply_hdr rhdr[1];
262 } reply_state;
264 // ***************************************************************************
265 #if COMPILER_LIKES_PRAGMA_MARK
266 #pragma mark -
267 #pragma mark - Globals
268 #endif
270 // globals
271 mDNSexport mDNS mDNSStorage;
272 mDNSexport const char ProgramName[] = "mDNSResponder";
274 static dnssd_sock_t listenfd = dnssd_InvalidSocket;
275 static request_state *all_requests = NULL;
276 #ifdef LOCAL_PEERPID
277 struct proc_bsdshortinfo proc;
278 #endif //LOCAL_PEERPID
279 mDNSlocal void set_peer_pid(request_state *request);
280 mDNSlocal void LogMcastClientInfo(request_state *req);
281 mDNSlocal void GetMcastClients(request_state *req);
282 static mDNSu32 mcount; // tracks the current active mcast operations for McastLogging
283 static mDNSu32 i_mcount; // sets mcount when McastLogging is enabled(PROF signal is sent)
284 static mDNSu32 n_mrecords; // tracks the current active mcast records for McastLogging
285 static mDNSu32 n_mquests; // tracks the current active mcast questions for McastLogging
287 // Note asymmetry here between registration and browsing.
288 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
289 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
290 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
291 // 1. SCPrefBrowseDomains (local configuration data)
292 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
293 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
294 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
296 mDNSexport DNameListElem *AutoRegistrationDomains; // Domains where we automatically register for empty-string registrations
298 static DNameListElem *SCPrefBrowseDomains; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
299 static ARListElem *LocalDomainEnumRecords; // List of locally-generated PTR records to augment those we learn from the network
300 mDNSexport DNameListElem *AutoBrowseDomains; // List created from those local-only PTR records plus records we get from the network
302 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
303 // n get_string() calls w/o buffer overrun
304 // initialization, setup/teardown functions
306 // If a platform specifies its own PID file name, we use that
307 #ifndef PID_FILE
308 #define PID_FILE "/var/run/mDNSResponder.pid"
309 #endif
311 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen);
313 // ***************************************************************************
314 #if COMPILER_LIKES_PRAGMA_MARK
315 #pragma mark -
316 #pragma mark - General Utility Functions
317 #endif
319 mDNSlocal void FatalError(char *errmsg)
321 LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
322 abort();
325 mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
327 mDNSu32 ret;
328 char *data = (char*) &ret;
329 put_uint32(l, &data);
330 return ret;
333 // hack to search-replace perror's to LogMsg's
334 mDNSlocal void my_perror(char *errmsg)
336 LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
339 // Throttled version of my_perror: Logs once every 250 msgs
340 mDNSlocal void my_throttled_perror(char *err_msg)
342 static int uds_throttle_count = 0;
343 if ((uds_throttle_count++ % 250) == 0)
344 my_perror(err_msg);
347 // LogMcastQuestion/LogMcastQ should be called after the DNSQuestion struct is initialized(especially for q->TargetQID)
348 // Hence all calls are made after mDNS_StartQuery()/mDNS_StopQuery()/mDNS_StopBrowse() is called.
349 mDNSlocal void LogMcastQuestion(mDNS *const m, const DNSQuestion *const q, request_state *req, q_state status)
351 if (mDNSOpaque16IsZero(q->TargetQID)) // Check for Mcast Query
353 mDNSBool mflag = mDNSfalse;
354 if (status == q_start)
356 if (++mcount == 1)
357 mflag = mDNStrue;
359 else
361 mcount--;
363 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Question" : "-Question", q->qname.c, DNSTypeName(q->qtype),
364 q->InterfaceID == mDNSInterface_LocalOnly ? "lo" : q->InterfaceID == mDNSInterface_P2P ? "p2p" :
365 q->InterfaceID == mDNSInterface_Any ? "any" : InterfaceNameForID(m, q->InterfaceID),
366 req->process_id, req->pid_name);
367 LogMcastStateInfo(m, mflag, mDNSfalse, mDNSfalse);
369 return;
372 // LogMcastService/LogMcastS should be called after the AuthRecord struct is initialized
373 // Hence all calls are made after mDNS_Register()/ just before mDNS_Deregister()
374 mDNSlocal void LogMcastService(mDNS *const m, const AuthRecord *const ar, request_state *req, reg_state status)
376 if (!AuthRecord_uDNS(ar)) // Check for Mcast Service
378 mDNSBool mflag = mDNSfalse;
379 if (status == reg_start)
381 if (++mcount == 1)
382 mflag = mDNStrue;
384 else
386 mcount--;
388 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Service" : "-Service", ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype),
389 ar->resrec.InterfaceID == mDNSInterface_LocalOnly ? "lo" : ar->resrec.InterfaceID == mDNSInterface_P2P ? "p2p" :
390 ar->resrec.InterfaceID == mDNSInterface_Any ? "all" : InterfaceNameForID(m, ar->resrec.InterfaceID),
391 req->process_id, req->pid_name);
392 LogMcastStateInfo(m, mflag, mDNSfalse, mDNSfalse);
394 return;
397 // For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
398 mDNSexport void LogMcastStateInfo(mDNS *const m, mDNSBool mflag, mDNSBool start, mDNSBool mstatelog)
400 if (!mstatelog)
402 if (!all_requests)
404 LogMcastNoIdent("<None>");
406 else
408 request_state *req, *r;
409 for (req = all_requests; req; req=req->next)
411 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
413 for (r = all_requests; r && r != req; r=r->next)
414 if (r == req->primary)
415 goto foundpar;
417 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
418 GetMcastClients(req);
419 foundpar:;
421 LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords, n_mquests);
422 n_mrecords = n_mquests = 0; // Reset the values
425 else
427 static mDNSu32 i_mpktnum;
428 i_mcount = 0;
429 if (start)
430 mcount = 0;
431 // mcount is initialized to 0 when the PROF signal is sent since mcount could have
432 // wrong value if MulticastLogging is disabled and then re-enabled
433 LogMcastNoIdent("--- START MCAST STATE LOG ---");
434 if (!all_requests)
436 mcount = 0;
437 LogMcastNoIdent("<None>");
439 else
441 request_state *req, *r;
442 for (req = all_requests; req; req=req->next)
444 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
446 for (r = all_requests; r && r != req; r=r->next)
447 if (r == req->primary)
448 goto foundparent;
449 LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req->sd);
451 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
452 LogMcastClientInfo(req);
453 foundparent:;
455 if(!mcount) // To initially set mcount
456 mcount = i_mcount;
458 if (mcount == 0)
460 i_mpktnum = m->MPktNum;
461 LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount, i_mpktnum);
463 if (mflag)
464 LogMcastNoIdent("--- MCOUNT[%d]: CMPKTNUM[%d] - IMPKTNUM[%d] = [%d]PKTS ---", mcount, m->MPktNum, i_mpktnum, (m->MPktNum - i_mpktnum));
465 LogMcastNoIdent("--- END MCAST STATE LOG ---");
469 mDNSlocal void abort_request(request_state *req)
471 if (req->terminate == (req_termination_fn) ~0)
472 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
474 // First stop whatever mDNSCore operation we were doing
475 // If this is actually a shared connection operation, then its req->terminate function will scan
476 // the all_requests list and terminate any subbordinate operations sharing this file descriptor
477 if (req->terminate) req->terminate(req);
479 if (!dnssd_SocketValid(req->sd))
480 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req, req->sd); return; }
482 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
483 if (!req->primary)
485 if (req->errsd != req->sd) LogOperation("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
486 else LogOperation("%3d: Removing FD", req->sd);
487 udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data); // Note: This also closes file descriptor req->sd for us
488 if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
490 while (req->replies) // free pending replies
492 reply_state *ptr = req->replies;
493 req->replies = req->replies->next;
494 freeL("reply_state (abort)", ptr);
498 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
499 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
500 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
501 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
502 req->sd = req->errsd = -2;
503 #else
504 req->sd = req->errsd = dnssd_InvalidSocket;
505 #endif
506 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
507 req->terminate = (req_termination_fn) ~0;
510 mDNSlocal void AbortUnlinkAndFree(request_state *req)
512 request_state **p = &all_requests;
513 abort_request(req);
514 while (*p && *p != req) p=&(*p)->next;
515 if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
516 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
519 mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
521 reply_state *reply;
523 if ((unsigned)datalen < sizeof(reply_hdr))
525 LogMsg("ERROR: create_reply - data length less than length of required fields");
526 return NULL;
529 reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
530 if (!reply) FatalError("ERROR: malloc");
532 reply->next = mDNSNULL;
533 reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
534 reply->nwriten = 0;
536 reply->mhdr->version = VERSION;
537 reply->mhdr->datalen = (mDNSu32)datalen;
538 reply->mhdr->ipc_flags = 0;
539 reply->mhdr->op = op;
540 reply->mhdr->client_context = request->hdr.client_context;
541 reply->mhdr->reg_index = 0;
543 return reply;
546 // Append a reply to the list in a request object
547 // If our request is sharing a connection, then we append our reply_state onto the primary's list
548 // If the request does not want asynchronous replies, then the reply is freed instead of being appended to any list.
549 mDNSlocal void append_reply(request_state *req, reply_state *rep)
551 request_state *r;
552 reply_state **ptr;
554 if (req->no_reply)
556 freeL("reply_state/append_reply", rep);
557 return;
560 r = req->primary ? req->primary : req;
561 ptr = &r->replies;
562 while (*ptr) ptr = &(*ptr)->next;
563 *ptr = rep;
564 rep->next = NULL;
567 // Generates a response message giving name, type, domain, plus interface index,
568 // suitable for a browse result or service registration result.
569 // On successful completion rep is set to point to a malloc'd reply_state struct
570 mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
571 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
573 domainlabel name;
574 domainname type, dom;
575 *rep = NULL;
576 if (!DeconstructServiceName(servicename, &name, &type, &dom))
577 return kDNSServiceErr_Invalid;
578 else
580 char namestr[MAX_DOMAIN_LABEL+1];
581 char typestr[MAX_ESCAPED_DOMAIN_NAME];
582 char domstr [MAX_ESCAPED_DOMAIN_NAME];
583 int len;
584 char *data;
586 ConvertDomainLabelToCString_unescaped(&name, namestr);
587 ConvertDomainNameToCString(&type, typestr);
588 ConvertDomainNameToCString(&dom, domstr);
590 // Calculate reply data length
591 len = sizeof(DNSServiceFlags);
592 len += sizeof(mDNSu32); // if index
593 len += sizeof(DNSServiceErrorType);
594 len += (int) (strlen(namestr) + 1);
595 len += (int) (strlen(typestr) + 1);
596 len += (int) (strlen(domstr) + 1);
598 // Build reply header
599 *rep = create_reply(op, len, request);
600 (*rep)->rhdr->flags = dnssd_htonl(flags);
601 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
602 (*rep)->rhdr->error = dnssd_htonl(err);
604 // Build reply body
605 data = (char *)&(*rep)->rhdr[1];
606 put_string(namestr, &data);
607 put_string(typestr, &data);
608 put_string(domstr, &data);
610 return mStatus_NoError;
614 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
615 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
616 mDNSlocal void GenerateBonjourBrowserResponse(const domainname *const servicename, const mDNSInterfaceID id,
617 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
619 char namestr[MAX_DOMAIN_LABEL+1];
620 char typestr[MAX_ESCAPED_DOMAIN_NAME];
621 static const char domstr[] = ".";
622 int len;
623 char *data;
625 *rep = NULL;
627 // 1. Put first label in namestr
628 ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
630 // 2. Put second label and "local" into typestr
631 mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
633 // Calculate reply data length
634 len = sizeof(DNSServiceFlags);
635 len += sizeof(mDNSu32); // if index
636 len += sizeof(DNSServiceErrorType);
637 len += (int) (strlen(namestr) + 1);
638 len += (int) (strlen(typestr) + 1);
639 len += (int) (strlen(domstr) + 1);
641 // Build reply header
642 *rep = create_reply(op, len, request);
643 (*rep)->rhdr->flags = dnssd_htonl(flags);
644 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
645 (*rep)->rhdr->error = dnssd_htonl(err);
647 // Build reply body
648 data = (char *)&(*rep)->rhdr[1];
649 put_string(namestr, &data);
650 put_string(typestr, &data);
651 put_string(domstr, &data);
654 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
655 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
656 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
657 mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
659 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
660 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
661 char name[256];
662 int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
663 mDNSu16 type = get_uint16(&request->msgptr, request->msgend);
664 mDNSu16 class = get_uint16(&request->msgptr, request->msgend);
665 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
666 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
667 mDNSu32 ttl = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
668 int storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
669 AuthRecord *rr;
670 mDNSInterfaceID InterfaceID;
671 AuthRecType artype;
673 request->flags = flags;
674 request->interfaceIndex = interfaceIndex;
676 if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
678 if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
680 if (validate_flags &&
681 !((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
682 !((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
684 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
685 return NULL;
688 rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
689 if (!rr) FatalError("ERROR: malloc");
691 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
692 if (InterfaceID == mDNSInterface_LocalOnly)
693 artype = AuthRecordLocalOnly;
694 else if (InterfaceID == mDNSInterface_P2P)
695 artype = AuthRecordP2P;
696 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
697 && (flags & kDNSServiceFlagsIncludeAWDL))
698 artype = AuthRecordAnyIncludeAWDLandP2P;
699 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
700 artype = AuthRecordAnyIncludeP2P;
701 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
702 artype = AuthRecordAnyIncludeAWDL;
703 else
704 artype = AuthRecordAny;
706 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
707 (mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
709 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
711 LogMsg("ERROR: bad name: %s", name);
712 freeL("AuthRecord/read_rr_from_ipc_msg", rr);
713 return NULL;
716 if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
717 rr->resrec.rrclass = class;
718 rr->resrec.rdlength = rdlen;
719 rr->resrec.rdata->MaxRDLength = rdlen;
720 mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
721 if (GetTTL) rr->resrec.rroriginalttl = ttl;
722 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
723 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
724 return rr;
727 mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
729 domainlabel n;
730 domainname d, t;
732 if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
733 if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
734 if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
735 if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
736 return 0;
739 mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
741 int n = send(s, ptr, len, 0);
742 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
743 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
744 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
745 if (n < len)
746 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
747 s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
750 #if 0
751 mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
753 const DNameListElem *delem = mDNSNULL;
754 int bestDelta = -1; // the delta of the best match, lower is better
755 int dLabels = 0;
756 mDNSBool allow = mDNSfalse;
758 if (SystemUID(request->uid)) return mDNStrue;
760 dLabels = CountLabels(d);
761 for (delem = doms; delem; delem = delem->next)
763 if (delem->uid)
765 int delemLabels = CountLabels(&delem->name);
766 int delta = dLabels - delemLabels;
767 if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
769 bestDelta = delta;
770 allow = (allow || (delem->uid == request->uid));
775 return bestDelta == -1 ? mDNStrue : allow;
777 #endif
779 // ***************************************************************************
780 #if COMPILER_LIKES_PRAGMA_MARK
781 #pragma mark -
782 #pragma mark - external helpers
783 #endif
785 mDNSlocal mDNSBool callExternalHelpers(mDNSInterfaceID InterfaceID, const domainname *const domain, DNSServiceFlags flags)
787 #if APPLE_OSX_mDNSResponder
789 if ( ((InterfaceID == mDNSInterface_Any) && (flags & (kDNSServiceFlagsIncludeP2P | kDNSServiceFlagsIncludeAWDL)) && IsLocalDomain(domain))
790 || mDNSPlatformInterfaceIsD2D(InterfaceID))
792 return mDNStrue;
794 else
795 return mDNSfalse;
797 #else
798 (void) InterfaceID;
799 (void) domain;
800 (void) flags;
802 return mDNSfalse;
803 #endif // APPLE_OSX_mDNSResponder
806 mDNSlocal void external_start_advertising_helper(service_instance *const instance)
808 AuthRecord *st = instance->subtypes;
809 ExtraResourceRecord *e;
810 int i;
812 if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
814 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
815 return;
818 if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
820 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
821 external_start_advertising_service(&st[i].resrec, instance->request->flags);
823 external_start_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
824 external_start_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
825 external_start_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
827 for (e = instance->srs.Extras; e; e = e->next)
828 external_start_advertising_service(&e->r.resrec, instance->request->flags);
830 instance->external_advertise = mDNStrue;
833 mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
835 AuthRecord *st = instance->subtypes;
836 ExtraResourceRecord *e;
837 int i;
839 if (!instance->external_advertise) return;
841 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
843 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
844 external_stop_advertising_service(&st[i].resrec, instance->request->flags);
846 external_stop_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
847 external_stop_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
848 external_stop_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
850 for (e = instance->srs.Extras; e; e = e->next)
851 external_stop_advertising_service(&e->r.resrec, instance->request->flags);
853 instance->external_advertise = mDNSfalse;
856 // ***************************************************************************
857 #if COMPILER_LIKES_PRAGMA_MARK
858 #pragma mark -
859 #pragma mark - DNSServiceRegister
860 #endif
862 mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
864 ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
865 (void)m; // Unused
867 if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
869 LogInfo(" FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
871 if (rr->resrec.rdata != &rr->rdatastorage)
872 freeL("Extra RData", rr->resrec.rdata);
873 freeL("ExtraResourceRecord/FreeExtraRR", extra);
876 mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
878 ExtraResourceRecord *e = srv->srs.Extras, *tmp;
880 external_stop_advertising_helper(srv);
882 // clear pointers from parent struct
883 if (srv->request)
885 service_instance **p = &srv->request->u.servicereg.instances;
886 while (*p)
888 if (*p == srv) { *p = (*p)->next; break; }
889 p = &(*p)->next;
893 while (e)
895 e->r.RecordContext = e;
896 tmp = e;
897 e = e->next;
898 FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
901 if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
902 freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
904 if (srv->subtypes)
906 freeL("ServiceSubTypes", srv->subtypes);
907 srv->subtypes = NULL;
909 if (srv->srs.AnonData)
911 freeL("Anonymous", (void *)srv->srs.AnonData);
912 srv->srs.AnonData = NULL;
914 freeL("service_instance", srv);
917 // Count how many other service records we have locally with the same name, but different rdata.
918 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
919 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
920 mDNSexport int CountPeerRegistrations(mDNS *const m, ServiceRecordSet *const srs)
922 int count = 0;
923 ResourceRecord *r = &srs->RR_SRV.resrec;
924 AuthRecord *rr;
926 for (rr = m->ResourceRecords; rr; rr=rr->next)
927 if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
928 count++;
930 verbosedebugf("%d peer registrations for %##s", count, r->name->c);
931 return(count);
934 mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
936 int count = 0;
937 AuthRecord *rr;
938 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
939 if (rr->resrec.rrtype == kDNSType_SRV &&
940 mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
941 SameDomainName(rr->resrec.name, srv))
942 count++;
943 return(count);
946 mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
948 reply_state *rep;
949 service_instance *instance = srs->ServiceContext;
950 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
951 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
952 else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
955 // service registration callback performs three duties - frees memory for deregistered services,
956 // handles name conflicts, and delivers completed registration information to the client
957 mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
959 mStatus err;
960 mDNSBool SuppressError = mDNSfalse;
961 service_instance *instance;
962 reply_state *rep;
963 (void)m; // Unused
965 if (!srs) { LogMsg("regservice_callback: srs is NULL %d", result); return; }
967 instance = srs->ServiceContext;
968 if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
970 // don't send errors up to client for wide-area, empty-string registrations
971 if (instance->request &&
972 instance->request->u.servicereg.default_domain &&
973 !instance->default_local)
974 SuppressError = mDNStrue;
976 if (mDNS_LoggingEnabled)
978 const char *const fmt =
979 (result == mStatus_NoError) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
980 (result == mStatus_MemFree) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
981 (result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
982 "%s DNSServiceRegister(%##s, %u) %s %d";
983 char prefix[16] = "---:";
984 if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
985 LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
986 SuppressError ? "suppressed error" : "CALLBACK", result);
989 if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
991 if (result == mStatus_NoError)
993 if (instance->request->u.servicereg.allowremotequery)
995 ExtraResourceRecord *e;
996 srs->RR_ADV.AllowRemoteQuery = mDNStrue;
997 srs->RR_PTR.AllowRemoteQuery = mDNStrue;
998 srs->RR_SRV.AllowRemoteQuery = mDNStrue;
999 srs->RR_TXT.AllowRemoteQuery = mDNStrue;
1000 for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
1003 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
1004 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
1005 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
1007 if (callExternalHelpers(instance->request->u.servicereg.InterfaceID, &instance->domain, instance->request->flags))
1009 LogInfo("regservice_callback: calling external_start_advertising_helper()");
1010 external_start_advertising_helper(instance);
1012 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
1013 RecordUpdatedNiceLabel(m, 0); // Successfully got new name, tell user immediately
1015 else if (result == mStatus_MemFree)
1017 if (instance->request && instance->renameonmemfree)
1019 external_stop_advertising_helper(instance);
1020 instance->renameonmemfree = 0;
1021 err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
1022 if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
1023 // error should never happen - safest to log and continue
1025 else
1026 unlink_and_free_service_instance(instance);
1028 else if (result == mStatus_NameConflict)
1030 if (instance->request->u.servicereg.autorename)
1032 external_stop_advertising_helper(instance);
1033 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
1035 // On conflict for an autoname service, rename and reregister *all* autoname services
1036 IncrementLabelSuffix(&m->nicelabel, mDNStrue);
1037 mDNS_ConfigChanged(m); // Will call back into udsserver_handle_configchange()
1039 else // On conflict for a non-autoname service, rename and reregister just that one service
1041 if (instance->clientnotified) SendServiceRemovalNotification(srs);
1042 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
1045 else
1047 if (!SuppressError)
1049 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
1050 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
1051 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
1053 unlink_and_free_service_instance(instance);
1056 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
1058 if (!SuppressError)
1060 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
1061 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
1062 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
1067 mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
1069 (void)m; // Unused
1070 if (!rr->RecordContext) // parent struct already freed by termination callback
1072 if (result == mStatus_NoError)
1073 LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
1074 else
1076 if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
1078 // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
1079 // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
1080 // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
1081 // to free the latest rdata for which the update_callback was never called with.
1082 if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
1083 freeL("AuthRecord/regrecord_callback", rr);
1086 else
1088 registered_record_entry *re = rr->RecordContext;
1089 request_state *request = re->request;
1091 if (mDNS_LoggingEnabled)
1093 char *fmt = (result == mStatus_NoError) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
1094 (result == mStatus_MemFree) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
1095 (result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
1096 "%3d: DNSServiceRegisterRecord(%u %s) %d";
1097 LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
1100 if (result != mStatus_MemFree)
1102 int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
1103 reply_state *reply = create_reply(reg_record_reply_op, len, request);
1104 reply->mhdr->client_context = re->regrec_client_context;
1105 reply->rhdr->flags = dnssd_htonl(0);
1106 reply->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
1107 reply->rhdr->error = dnssd_htonl(result);
1108 append_reply(request, reply);
1111 if (result)
1113 // If this is a callback to a keepalive record, do not free it.
1114 if (result == mStatus_BadStateErr)
1116 LogInfo("regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.");
1118 else
1120 // unlink from list, free memory
1121 registered_record_entry **ptr = &request->u.reg_recs;
1122 while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
1123 if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
1124 *ptr = (*ptr)->next;
1125 freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
1126 freeL("registered_record_entry regrecord_callback", re);
1129 else
1131 if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
1133 if (callExternalHelpers(re->origInterfaceID, &rr->namestorage, request->flags))
1135 LogInfo("regrecord_callback: calling external_start_advertising_service");
1136 external_start_advertising_service(&rr->resrec, request->flags);
1137 re->external_advertise = mDNStrue;
1143 // set_peer_pid() is called after mem is allocated for each new request in NewRequest()
1144 // This accounts for 2 places (connect_callback, request_callback)
1145 mDNSlocal void set_peer_pid(request_state *request)
1147 #ifdef LOCAL_PEERPID
1148 pid_t p = (pid_t) -1;
1149 socklen_t len = sizeof(p);
1151 request->pid_name[0] = '\0';
1152 request->process_id = -1;
1154 if (request->sd < 0)
1155 return;
1156 // to extract the pid value
1157 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEERPID, &p, &len) != 0)
1158 return;
1159 // to extract the process name from the pid value
1160 if (proc_pidinfo(p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
1161 return;
1162 mDNSPlatformStrCopy(request->pid_name, proc.pbsi_comm);
1163 request->process_id = p;
1164 debugf("set_peer_pid: Client PEERPID is %d %s", p, request->pid_name);
1165 #else // !LOCAL_PEERPID
1166 request->pid_name[0] = '\0';
1167 request->process_id = -1;
1169 LogInfo("set_peer_pid: Not Supported on this version of OS");
1170 if (request->sd < 0)
1171 return;
1172 #endif // LOCAL_PEERPID
1175 mDNSlocal void connection_termination(request_state *request)
1177 // When terminating a shared connection, we need to scan the all_requests list
1178 // and terminate any subbordinate operations sharing this file descriptor
1179 request_state **req = &all_requests;
1181 LogOperation("%3d: DNSServiceCreateConnection STOP PID[%d](%s)", request->sd, request->process_id, request->pid_name);
1183 while (*req)
1185 if ((*req)->primary == request)
1187 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1188 request_state *tmp = *req;
1189 if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp, tmp->sd);
1190 if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
1191 abort_request(tmp);
1192 *req = tmp->next;
1193 freeL("request_state/connection_termination", tmp);
1195 else
1196 req = &(*req)->next;
1199 while (request->u.reg_recs)
1201 registered_record_entry *ptr = request->u.reg_recs;
1202 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP PID[%d](%s)", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec), request->process_id, request->pid_name);
1203 request->u.reg_recs = request->u.reg_recs->next;
1204 ptr->rr->RecordContext = NULL;
1205 if (ptr->external_advertise)
1207 ptr->external_advertise = mDNSfalse;
1208 external_stop_advertising_service(&ptr->rr->resrec, request->flags);
1210 LogMcastS(&mDNSStorage, ptr->rr, request, reg_stop);
1211 mDNS_Deregister(&mDNSStorage, ptr->rr); // Will free ptr->rr for us
1212 freeL("registered_record_entry/connection_termination", ptr);
1216 mDNSlocal void handle_cancel_request(request_state *request)
1218 request_state **req = &all_requests;
1219 LogOperation("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
1220 while (*req)
1222 if ((*req)->primary == request &&
1223 (*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1224 (*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
1226 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1227 request_state *tmp = *req;
1228 abort_request(tmp);
1229 *req = tmp->next;
1230 freeL("request_state/handle_cancel_request", tmp);
1232 else
1233 req = &(*req)->next;
1237 mDNSlocal mStatus handle_regrecord_request(request_state *request)
1239 mStatus err = mStatus_BadParamErr;
1240 AuthRecord *rr = read_rr_from_ipc_msg(request, 1, 1);
1241 if (rr)
1243 registered_record_entry *re;
1244 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1245 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1246 if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
1247 rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
1248 rr->resrec.rrtype == kDNSType_CNAME))
1250 freeL("AuthRecord/handle_regrecord_request", rr);
1251 return (mStatus_BadParamErr);
1253 // allocate registration entry, link into list
1254 re = mallocL("registered_record_entry", sizeof(registered_record_entry));
1255 if (!re)
1256 FatalError("ERROR: malloc");
1257 re->key = request->hdr.reg_index;
1258 re->rr = rr;
1259 re->regrec_client_context = request->hdr.client_context;
1260 re->request = request;
1261 re->external_advertise = mDNSfalse;
1262 rr->RecordContext = re;
1263 rr->RecordCallback = regrecord_callback;
1265 re->origInterfaceID = rr->resrec.InterfaceID;
1266 if (rr->resrec.InterfaceID == mDNSInterface_P2P)
1267 rr->resrec.InterfaceID = mDNSInterface_Any;
1268 #if 0
1269 if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError);
1270 #endif
1271 if (rr->resrec.rroriginalttl == 0)
1272 rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);
1274 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START PID[%d](%s)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec),
1275 request->process_id, request->pid_name);
1277 err = mDNS_Register(&mDNSStorage, rr);
1278 if (err)
1280 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec), err);
1281 freeL("registered_record_entry", re);
1282 freeL("registered_record_entry/AuthRecord", rr);
1284 else
1286 LogMcastS(&mDNSStorage, rr, request, reg_start);
1287 re->next = request->u.reg_recs;
1288 request->u.reg_recs = re;
1291 return(err);
1294 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);
1296 mDNSlocal void regservice_termination_callback(request_state *request)
1298 if (!request)
1300 LogMsg("regservice_termination_callback context is NULL");
1301 return;
1303 while (request->u.servicereg.instances)
1305 service_instance *p = request->u.servicereg.instances;
1306 request->u.servicereg.instances = request->u.servicereg.instances->next;
1307 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1308 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP PID[%d](%s)", request->sd, p->srs.RR_SRV.resrec.name->c,
1309 mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port), request->process_id, request->pid_name);
1311 external_stop_advertising_helper(p);
1313 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1314 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1315 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1316 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1317 // because by then we might have already freed p
1318 p->request = NULL;
1319 LogMcastS(&mDNSStorage, &p->srs.RR_SRV, request, reg_stop);
1320 if (mDNS_DeregisterService(&mDNSStorage, &p->srs))
1322 unlink_and_free_service_instance(p);
1323 // Don't touch service_instance *p after this -- it's likely to have been freed already
1326 if (request->u.servicereg.txtdata)
1328 freeL("service_info txtdata", request->u.servicereg.txtdata);
1329 request->u.servicereg.txtdata = NULL;
1331 if (request->u.servicereg.autoname)
1333 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1334 request->u.servicereg.autoname = mDNSfalse;
1335 UpdateDeviceInfoRecord(&mDNSStorage);
1339 mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
1341 request_state *req;
1342 for (req = all_requests; req; req = req->next)
1343 if (req->primary == request &&
1344 req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1345 req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
1346 return(request);
1349 mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl)
1351 ServiceRecordSet *srs = &instance->srs;
1352 mStatus result;
1353 mDNSu32 coreFlags = 0; // translate to corresponding mDNSCore flag definitions
1354 int size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1355 ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
1356 if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1358 mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord)); // OK if oversized rdata not zero'd
1359 extra->r.resrec.rrtype = rrtype;
1360 extra->r.rdatastorage.MaxRDLength = (mDNSu16) size;
1361 extra->r.resrec.rdlength = rdlen;
1362 mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen);
1363 // use InterfaceID value from DNSServiceRegister() call that created the original service
1364 extra->r.resrec.InterfaceID = request->u.servicereg.InterfaceID;
1366 if (request->flags & kDNSServiceFlagsIncludeP2P)
1367 coreFlags |= coreFlagIncludeP2P;
1368 if (request->flags & kDNSServiceFlagsIncludeAWDL)
1369 coreFlags |= coreFlagIncludeAWDL;
1371 result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl, coreFlags);
1372 if (result)
1374 freeL("ExtraResourceRecord/add_record_to_service", extra);
1375 return result;
1377 LogMcastS(&mDNSStorage, &srs->RR_PTR, request, reg_start);
1379 extra->ClientID = request->hdr.reg_index;
1380 if ( instance->external_advertise
1381 && callExternalHelpers(request->u.servicereg.InterfaceID, &instance->domain, request->flags))
1383 LogInfo("add_record_to_service: calling external_start_advertising_service");
1384 external_start_advertising_service(&extra->r.resrec, request->flags);
1386 return result;
1389 mDNSlocal mStatus handle_add_request(request_state *request)
1391 service_instance *i;
1392 mStatus result = mStatus_UnknownErr;
1393 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);
1394 mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend);
1395 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1396 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1397 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1398 if (!ttl) ttl = DefaultTTLforRRType(rrtype);
1399 (void)flags; // Unused
1401 if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1403 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1404 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1406 if (request->terminate != regservice_termination_callback)
1407 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1409 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1410 // in the application. See radar://9165807.
1411 if (mDNSIPPortIsZero(request->u.servicereg.port))
1412 { LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1414 LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d)", request->sd, flags,
1415 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen);
1417 for (i = request->u.servicereg.instances; i; i = i->next)
1419 result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
1420 if (result && i->default_local) break;
1421 else result = mStatus_NoError; // suppress non-local default errors
1424 return(result);
1427 mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
1429 mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
1430 (void)m; // Unused
1432 // There are three cases.
1434 // 1. We have updated the primary TXT record of the service
1435 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1436 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1438 // external_advertise is set if we have advertised at least once during the initial addition
1439 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1440 // checks during the first time and hence we don't do any checks here
1441 if (external_advertise)
1443 ResourceRecord ext = rr->resrec;
1444 DNSServiceFlags flags = 0;
1446 // Since we don't have a copy of the flags value used when the record was registered,
1447 // we'll have to derive it from the ARType field.
1448 if (rr->ARType == AuthRecordAnyIncludeP2P)
1449 flags |= kDNSServiceFlagsIncludeP2P;
1450 else if (rr->ARType == AuthRecordAnyIncludeAWDL)
1451 flags |= kDNSServiceFlagsIncludeAWDL;
1453 if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
1454 SetNewRData(&ext, oldrd, oldrdlen);
1455 external_stop_advertising_service(&ext, flags);
1456 LogInfo("update_callback: calling external_start_advertising_service");
1457 external_start_advertising_service(&rr->resrec, flags);
1459 exit:
1460 if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
1463 mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl, const mDNSBool *const external_advertise)
1465 mStatus result;
1466 const int rdsize = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1467 RData *newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize);
1468 if (!newrd) FatalError("ERROR: malloc");
1469 newrd->MaxRDLength = (mDNSu16) rdsize;
1470 mDNSPlatformMemCopy(&newrd->u, rdata, rdlen);
1472 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1473 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1474 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1475 if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }
1477 if (external_advertise) rr->UpdateContext = (void *)external_advertise;
1479 result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback);
1480 if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, rr)); freeL("RData/update_record", newrd); }
1481 return result;
1484 mDNSlocal mStatus handle_update_request(request_state *request)
1486 const ipc_msg_hdr *const hdr = &request->hdr;
1487 mStatus result = mStatus_BadReferenceErr;
1488 service_instance *i;
1489 AuthRecord *rr = NULL;
1491 // get the message data
1492 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend); // flags unused
1493 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1494 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1495 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1496 (void)flags; // Unused
1498 if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1500 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1501 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1503 if (request->terminate == connection_termination)
1505 // update an individually registered record
1506 registered_record_entry *reptr;
1507 for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
1509 if (reptr->key == hdr->reg_index)
1511 result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise);
1512 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)",
1513 request->sd, reptr->rr->resrec.name->c, reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>");
1514 goto end;
1517 result = mStatus_BadReferenceErr;
1518 goto end;
1521 if (request->terminate != regservice_termination_callback)
1522 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1524 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1525 if (mDNSIPPortIsZero(request->u.servicereg.port))
1526 { LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1528 // update the saved off TXT data for the service
1529 if (hdr->reg_index == TXT_RECORD_INDEX)
1531 if (request->u.servicereg.txtdata)
1532 { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
1533 if (rdlen > 0)
1535 request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
1536 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
1537 mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
1539 request->u.servicereg.txtlen = rdlen;
1542 // update a record from a service record set
1543 for (i = request->u.servicereg.instances; i; i = i->next)
1545 if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
1546 else
1548 ExtraResourceRecord *e;
1549 for (e = i->srs.Extras; e; e = e->next)
1550 if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
1553 if (!rr) { result = mStatus_BadReferenceErr; goto end; }
1554 result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise);
1555 if (result && i->default_local) goto end;
1556 else result = mStatus_NoError; // suppress non-local default errors
1559 end:
1560 if (request->terminate == regservice_termination_callback)
1561 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request->sd,
1562 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1563 rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>");
1565 return(result);
1568 // remove a resource record registered via DNSServiceRegisterRecord()
1569 mDNSlocal mStatus remove_record(request_state *request)
1571 mStatus err = mStatus_UnknownErr;
1572 registered_record_entry *e, **ptr = &request->u.reg_recs;
1574 while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
1575 if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
1576 e = *ptr;
1577 *ptr = e->next; // unlink
1579 LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec));
1580 e->rr->RecordContext = NULL;
1581 if (e->external_advertise)
1583 external_stop_advertising_service(&e->rr->resrec, request->flags);
1584 e->external_advertise = mDNSfalse;
1586 LogMcastS(&mDNSStorage, e->rr, request, reg_stop);
1587 err = mDNS_Deregister(&mDNSStorage, e->rr); // Will free e->rr for us; we're responsible for freeing e
1588 if (err)
1590 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
1591 freeL("registered_record_entry AuthRecord remove_record", e->rr);
1593 freeL("registered_record_entry remove_record", e);
1594 return err;
1597 mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
1599 mStatus err = mStatus_BadReferenceErr;
1600 ExtraResourceRecord *ptr;
1602 for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
1604 if (ptr->ClientID == request->hdr.reg_index) // found match
1606 *rrtype = ptr->r.resrec.rrtype;
1607 if (serv->external_advertise) external_stop_advertising_service(&ptr->r.resrec, request->flags);
1608 err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
1609 break;
1612 return err;
1615 mDNSlocal mStatus handle_removerecord_request(request_state *request)
1617 mStatus err = mStatus_BadReferenceErr;
1618 get_flags(&request->msgptr, request->msgend); // flags unused
1620 if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1622 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1623 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1625 if (request->terminate == connection_termination)
1626 err = remove_record(request); // remove individually registered record
1627 else if (request->terminate != regservice_termination_callback)
1628 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1629 else
1631 service_instance *i;
1632 mDNSu16 rrtype = 0;
1633 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request->sd,
1634 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1635 rrtype ? DNSTypeName(rrtype) : "<NONE>");
1636 for (i = request->u.servicereg.instances; i; i = i->next)
1638 err = remove_extra(request, i, &rrtype);
1639 if (err && i->default_local) break;
1640 else err = mStatus_NoError; // suppress non-local default errors
1644 return(err);
1647 // If there's a comma followed by another character,
1648 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1649 // Otherwise, it returns a pointer to the final nul at the end of the string
1650 mDNSlocal char *FindFirstSubType(char *p, char **AnonData)
1652 while (*p)
1654 if (p[0] == '\\' && p[1])
1656 p += 2;
1658 else if (p[0] == ',' && p[1])
1660 *p++ = 0;
1661 return(p);
1663 else if (p[0] == ':' && p[1])
1665 *p++ = 0;
1666 *AnonData = p;
1668 else
1670 p++;
1673 return(p);
1676 // If there's a comma followed by another character,
1677 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1678 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1679 // Otherwise, it returns a pointer to the final nul at the end of the string
1680 mDNSlocal char *FindNextSubType(char *p)
1682 while (*p)
1684 if (p[0] == '\\' && p[1]) // If escape character
1685 p += 2; // ignore following character
1686 else if (p[0] == ',') // If we found a comma
1688 if (p[1]) *p++ = 0;
1689 return(p);
1691 else if (p[0] == '.')
1692 return(mDNSNULL);
1693 else p++;
1695 return(p);
1698 // Returns -1 if illegal subtype found
1699 mDNSexport mDNSs32 ChopSubTypes(char *regtype, char **AnonData)
1701 mDNSs32 NumSubTypes = 0;
1702 char *stp = FindFirstSubType(regtype, AnonData);
1703 while (stp && *stp) // If we found a comma...
1705 if (*stp == ',') return(-1);
1706 NumSubTypes++;
1707 stp = FindNextSubType(stp);
1709 if (!stp) return(-1);
1710 return(NumSubTypes);
1713 mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p, char **AnonData)
1715 AuthRecord *st = mDNSNULL;
1717 // "p" is pointing at the regtype e.g., _http._tcp followed by ":<AnonData>" indicated
1718 // by AnonData being non-NULL which is in turn follwed by ",<SubTypes>" indicated by
1719 // NumSubTypes being non-zero. We need to skip the initial regtype to get to the actual
1720 // data that we want. When we come here, ChopSubTypes has null terminated like this e.g.,
1722 // _http._tcp<NULL><AnonData><NULL><SubType1><NULL><SubType2><NULL> etc.
1724 // 1. If we have Anonymous data and subtypes, skip the regtype (e.g., "_http._tcp")
1725 // to get the AnonData and then skip the AnonData to get to the SubType.
1727 // 2. If we have only SubTypes, skip the regtype to get to the SubType data.
1729 // 3. If we have only AnonData, skip the regtype to get to the AnonData.
1731 // 4. If we don't have AnonData or NumStypes, it is a noop.
1733 if (AnonData)
1735 int len;
1737 // Skip the regtype
1738 while (*p) p++;
1739 p++;
1741 len = strlen(p) + 1;
1742 *AnonData = mallocL("Anonymous", len);
1743 if (!(*AnonData))
1745 return (mDNSNULL);
1747 mDNSPlatformMemCopy(*AnonData, p, len);
1749 if (NumSubTypes)
1751 mDNSs32 i;
1752 st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
1753 if (!st) return(mDNSNULL);
1754 for (i = 0; i < NumSubTypes; i++)
1756 mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
1757 // First time through we skip the regtype or AnonData. Subsequently, the
1758 // previous subtype.
1759 while (*p) p++;
1760 p++;
1761 if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
1763 freeL("ServiceSubTypes", st);
1764 if (*AnonData)
1765 freeL("AnonymousData", *AnonData);
1766 return(mDNSNULL);
1770 // If NumSubTypes is zero and AnonData is non-NULL, we still return NULL but AnonData has been
1771 // initialized. The caller knows how to handle this.
1772 return(st);
1775 mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
1777 service_instance **ptr, *instance;
1778 const int extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
1779 const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
1780 mStatus result;
1781 mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;
1782 mDNSu32 coreFlags = 0;
1784 if (request->flags & kDNSServiceFlagsIncludeP2P)
1785 coreFlags |= coreFlagIncludeP2P;
1786 if (request->flags & kDNSServiceFlagsIncludeAWDL)
1787 coreFlags |= coreFlagIncludeAWDL;
1789 // Client guarantees that record names are unique, so we can skip sending out initial
1790 // probe messages. Standard name conflict resolution is still done if a conflict is discovered.
1791 if (request->flags & kDNSServiceFlagsKnownUnique)
1792 coreFlags |= coreFlagKnownUnique;
1794 if (request->flags & kDNSServiceFlagsWakeOnlyService)
1795 coreFlags |= coreFlagWakeOnly;
1797 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1798 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1799 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1800 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1801 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1802 if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;
1804 for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
1806 if (SameDomainName(&(*ptr)->domain, domain))
1808 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1809 domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
1810 return mStatus_AlreadyRegistered;
1814 instance = mallocL("service_instance", sizeof(*instance) + extra_size);
1815 if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1817 instance->next = mDNSNULL;
1818 instance->request = request;
1819 instance->renameonmemfree = 0;
1820 instance->clientnotified = mDNSfalse;
1821 instance->default_local = (request->u.servicereg.default_domain && DomainIsLocal);
1822 instance->external_advertise = mDNSfalse;
1823 AssignDomainName(&instance->domain, domain);
1825 instance->srs.AnonData = mDNSNULL;
1826 if (!request->u.servicereg.AnonData)
1828 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, mDNSNULL);
1830 else
1832 char *AnonData = mDNSNULL;
1833 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, &AnonData);
1834 if (AnonData)
1835 instance->srs.AnonData = (const mDNSu8 *)AnonData;
1838 if (request->u.servicereg.num_subtypes && !instance->subtypes)
1840 unlink_and_free_service_instance(instance);
1841 instance = NULL;
1842 FatalError("ERROR: malloc");
1845 result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
1846 &request->u.servicereg.name, &request->u.servicereg.type, domain,
1847 request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
1848 request->u.servicereg.port,
1849 request->u.servicereg.txtdata, request->u.servicereg.txtlen,
1850 instance->subtypes, request->u.servicereg.num_subtypes,
1851 interfaceID, regservice_callback, instance, coreFlags);
1853 if (!result)
1855 *ptr = instance; // Append this to the end of our request->u.servicereg.instances list
1856 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance->request->sd,
1857 instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
1858 LogMcastS(&mDNSStorage, &instance->srs.RR_SRV, request, reg_start);
1860 else
1862 LogMsg("register_service_instance %#s.%##s%##s error %d",
1863 &request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
1864 unlink_and_free_service_instance(instance);
1867 return result;
1870 mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
1872 request_state *request;
1874 #if APPLE_OSX_mDNSResponder
1875 machserver_automatic_registration_domain_changed(&d->name, add);
1876 #endif // APPLE_OSX_mDNSResponder
1878 LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
1879 for (request = all_requests; request; request = request->next)
1881 if (request->terminate != regservice_termination_callback) continue;
1882 if (!request->u.servicereg.default_domain) continue;
1883 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1885 service_instance **ptr = &request->u.servicereg.instances;
1886 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1887 if (add)
1889 // If we don't already have this domain in our list for this registration, add it now
1890 if (!*ptr) register_service_instance(request, &d->name);
1891 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
1893 else
1895 // Normally we should not fail to find the specified instance
1896 // One case where this can happen is if a uDNS update fails for some reason,
1897 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1898 if (!*ptr)
1899 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1900 &d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
1901 else
1903 DNameListElem *p;
1904 for (p = AutoRegistrationDomains; p; p=p->next)
1905 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1906 if (SameDomainName(&d->name, &p->name)) break;
1907 if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
1908 else
1910 mStatus err;
1911 service_instance *si = *ptr;
1912 *ptr = si->next;
1913 if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
1914 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1915 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1916 // process of completing asynchronously, the client cancels the entire operation, so
1917 // regservice_termination_callback then runs through the whole list deregistering each
1918 // instance, clearing the backpointers, and then disposing the parent request_state object.
1919 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1920 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1921 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1922 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1923 si->request = NULL;
1924 err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
1925 if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
1933 // Don't allow normal and anonymous registration to coexist.
1934 mDNSlocal mDNSBool CheckForMixedRegistrations(domainname *regtype, domainname *domain, mDNSBool AnonData)
1936 request_state *request;
1938 // We only care about local domains where the anonymous extension is
1939 // implemented.
1940 if (!SameDomainName(domain, (const domainname *) "\x5" "local"))
1942 return mDNStrue;
1945 for (request = all_requests; request; request = request->next)
1947 service_instance *ptr;
1949 if (request->terminate != regservice_termination_callback) continue;
1950 for (ptr = request->u.servicereg.instances; ptr ; ptr = ptr->next)
1952 if (!SameDomainName(&ptr->domain, (const domainname *)"\x5" "local") ||
1953 !SameDomainName(&request->u.servicereg.type, regtype))
1955 continue;
1958 // If we are about to register a anonymous registraion, we dont't want to
1959 // allow the regular ones and vice versa.
1960 if (AnonData)
1962 if (!ptr->srs.AnonData)
1964 LogMsg("CheckForMixedRegistrations: Normal registration already exists for %##s", regtype->c);
1965 return mDNSfalse;
1968 else
1970 // Allow multiple regular registrations
1971 if (ptr->srs.AnonData)
1973 LogMsg("CheckForMixedRegistrations: Anonymous registration already exists for %##s", regtype->c);
1974 return mDNSfalse;
1979 return mDNStrue;
1982 // Returns true if the interfaceIndex value matches one of the pre-defined
1983 // special values listed in the switch statement below.
1984 mDNSlocal mDNSBool PreDefinedInterfaceIndex(mDNSu32 interfaceIndex)
1986 switch(interfaceIndex)
1988 case kDNSServiceInterfaceIndexAny:
1989 case kDNSServiceInterfaceIndexLocalOnly:
1990 case kDNSServiceInterfaceIndexUnicast:
1991 case kDNSServiceInterfaceIndexP2P:
1992 return mDNStrue;
1993 default:
1994 return mDNSfalse;
1998 mDNSlocal mStatus handle_regservice_request(request_state *request)
2000 char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
2001 char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
2002 char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
2003 domainname d, srv;
2004 mStatus err;
2005 char *AnonData = mDNSNULL;
2006 const char *msgTXTData;
2008 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2009 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2010 mDNSInterfaceID InterfaceID;
2012 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
2013 // kDNSServiceFlagsIncludeP2P flag set.
2014 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
2016 LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2017 flags |= kDNSServiceFlagsIncludeP2P;
2018 interfaceIndex = kDNSServiceInterfaceIndexAny;
2021 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2023 // The registration is scoped to a specific interface index, but the
2024 // interface is not currently in our list.
2025 if (interfaceIndex && !InterfaceID)
2027 // If it's one of the specially defined inteface index values, just return an error.
2028 if (PreDefinedInterfaceIndex(interfaceIndex))
2030 LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex);
2031 return(mStatus_BadParamErr);
2034 // Otherwise, use the specified interface index value and the registration will
2035 // be applied to that interface when it comes up.
2036 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2037 LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex);
2040 if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
2041 get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2042 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2043 get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
2044 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2046 request->flags = flags;
2047 request->interfaceIndex = interfaceIndex;
2048 request->u.servicereg.InterfaceID = InterfaceID;
2049 request->u.servicereg.instances = NULL;
2050 request->u.servicereg.txtlen = 0;
2051 request->u.servicereg.txtdata = NULL;
2052 mDNSPlatformStrCopy(request->u.servicereg.type_as_string, type_as_string);
2054 if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
2055 else
2057 request->u.servicereg.port.b[0] = *request->msgptr++;
2058 request->u.servicereg.port.b[1] = *request->msgptr++;
2061 request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
2062 msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);
2064 if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2066 if (request->u.servicereg.txtlen)
2068 request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
2069 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
2070 mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
2073 // Check for sub-types after the service type
2074 request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
2075 if (request->u.servicereg.num_subtypes < 0)
2077 LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string);
2078 goto bad_param;
2080 if (AnonData)
2082 int AnonDataLen = strlen(AnonData);
2083 if (AnonDataLen > MAX_ANONYMOUS_DATA)
2085 LogMsg("ERROR: handle_regservice_request: AnonDataLen %d", AnonDataLen);
2086 goto bad_param;
2088 request->u.servicereg.AnonData = mDNStrue;
2090 else
2092 request->u.servicereg.AnonData = mDNSfalse;
2095 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
2096 if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
2097 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); goto bad_param; }
2099 if (!name[0])
2101 request->u.servicereg.name = mDNSStorage.nicelabel;
2102 request->u.servicereg.autoname = mDNStrue;
2104 else
2106 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
2107 if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
2109 int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
2110 name[newlen] = 0;
2112 if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
2113 { LogMsg("ERROR: handle_regservice_request - name bad %s", name); goto bad_param; }
2114 request->u.servicereg.autoname = mDNSfalse;
2117 if (*domain)
2119 request->u.servicereg.default_domain = mDNSfalse;
2120 if (!MakeDomainNameFromDNSNameString(&d, domain))
2121 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); goto bad_param; }
2123 else
2125 request->u.servicereg.default_domain = mDNStrue;
2126 MakeDomainNameFromDNSNameString(&d, "local.");
2129 // We don't allow the anonymous and the regular ones to coexist
2130 if (!CheckForMixedRegistrations(&request->u.servicereg.type, &d, request->u.servicereg.AnonData)) { goto bad_param; }
2132 if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
2134 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
2135 request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); goto bad_param;
2138 if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
2139 { LogMsg("ERROR: handle_regservice_request - host bad %s", host); goto bad_param; }
2140 request->u.servicereg.autorename = (flags & kDNSServiceFlagsNoAutoRename ) == 0;
2141 request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
2143 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
2144 // a port number of zero. When two instances of the protected client are allowed to run on one
2145 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
2146 if (!mDNSIPPortIsZero(request->u.servicereg.port))
2148 int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
2149 if (count)
2150 LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request->process_id,
2151 request->pid_name, count+1, srv.c, mDNSVal16(request->u.servicereg.port));
2154 LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START PID[%d](%s)",
2155 request->sd, flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host,
2156 mDNSVal16(request->u.servicereg.port), request->process_id, request->pid_name);
2158 // We need to unconditionally set request->terminate, because even if we didn't successfully
2159 // start any registrations right now, subsequent configuration changes may cause successful
2160 // registrations to be added, and we'll need to cancel them before freeing this memory.
2161 // We also need to set request->terminate first, before adding additional service instances,
2162 // because the uds_validatelists uses the request->terminate function pointer to determine
2163 // what kind of request this is, and therefore what kind of list validation is required.
2164 request->terminate = regservice_termination_callback;
2166 err = register_service_instance(request, &d);
2168 #if 0
2169 err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
2170 #endif
2171 if (!err)
2173 if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
2175 if (!*domain)
2177 DNameListElem *ptr;
2178 // Note that we don't report errors for non-local, non-explicit domains
2179 for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
2180 if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
2181 register_service_instance(request, &ptr->name);
2185 return(err);
2187 bad_param:
2188 freeL("handle_regservice_request (txtdata)", request->u.servicereg.txtdata);
2189 request->u.servicereg.txtdata = NULL;
2190 return mStatus_BadParamErr;
2193 // ***************************************************************************
2194 #if COMPILER_LIKES_PRAGMA_MARK
2195 #pragma mark -
2196 #pragma mark - DNSServiceBrowse
2197 #endif
2199 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2201 DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
2202 request_state *req = question->QuestionContext;
2203 reply_state *rep;
2204 (void)m; // Unused
2206 if (answer->rrtype != kDNSType_PTR)
2207 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
2209 if (mDNSOpaque16IsZero(question->TargetQID) && (question->BrowseThreshold > 0) && (question->CurrentAnswers >= question->BrowseThreshold))
2211 flags |= kDNSServiceFlagsThresholdReached;
2214 if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
2216 if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
2218 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2219 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2220 GenerateBonjourBrowserResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
2221 goto bonjourbrowserhack;
2224 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2225 req->sd, answer->name->c, answer->rdata->u.name.c);
2226 return;
2229 bonjourbrowserhack:
2231 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
2232 req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "Add" : "Rmv",
2233 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2235 append_reply(req, rep);
2238 mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
2240 browser_t *b, *p;
2241 mStatus err;
2243 for (p = info->u.browser.browsers; p; p = p->next)
2245 if (SameDomainName(&p->domain, d))
2246 { debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
2249 b = mallocL("browser_t", sizeof(*b));
2250 if (!b) return mStatus_NoMemoryErr;
2251 AssignDomainName(&b->domain, d);
2252 err = mDNS_StartBrowse(&mDNSStorage, &b->q, &info->u.browser.regtype, d, info->u.browser.AnonData, info->u.browser.interface_id, info->flags,
2253 info->u.browser.ForceMCast, (info->flags & kDNSServiceFlagsBackgroundTrafficClass) != 0, FoundInstance, info);
2254 if (err)
2256 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
2257 freeL("browser_t/add_domain_to_browser", b);
2259 else
2261 b->next = info->u.browser.browsers;
2262 info->u.browser.browsers = b;
2263 LogOperation("%3d: DNSServiceBrowse(%##s) START PID[%d](%s)", info->sd, b->q.qname.c, info->process_id,
2264 info->pid_name);
2265 LogMcastQ(&mDNSStorage, &b->q, info, q_start);
2266 if (callExternalHelpers(info->u.browser.interface_id, &b->domain, info->flags))
2268 domainname tmp;
2269 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
2270 LogInfo("add_domain_to_browser: calling external_start_browsing_for_service()");
2271 external_start_browsing_for_service(info->u.browser.interface_id, &tmp, kDNSType_PTR, info->flags);
2274 return err;
2277 mDNSlocal void browse_termination_callback(request_state *info)
2279 if (info->u.browser.default_domain)
2281 // Stop the domain enumeration queries to discover the WAB legacy browse domains
2282 LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info->sd, info->process_id, info->pid_name);
2283 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2285 if (info->u.browser.AnonData)
2286 freeL("Anonymous", (void *)info->u.browser.AnonData);
2287 while (info->u.browser.browsers)
2289 browser_t *ptr = info->u.browser.browsers;
2291 if (callExternalHelpers(info->u.browser.interface_id, &ptr->domain, info->flags))
2293 domainname tmp;
2294 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
2295 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2296 external_stop_browsing_for_service(info->u.browser.interface_id, &tmp, kDNSType_PTR, info->flags);
2299 info->u.browser.browsers = ptr->next;
2300 LogOperation("%3d: DNSServiceBrowse(%##s) STOP PID[%d](%s)", info->sd, ptr->q.qname.c, info->process_id, info->pid_name);
2301 mDNS_StopBrowse(&mDNSStorage, &ptr->q); // no need to error-check result
2302 LogMcastQ(&mDNSStorage, &ptr->q, info, q_stop);
2303 freeL("browser_t/browse_termination_callback", ptr);
2307 mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
2309 request_state *request;
2310 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
2312 #if APPLE_OSX_mDNSResponder
2313 machserver_automatic_browse_domain_changed(&d->name, add);
2314 #endif // APPLE_OSX_mDNSResponder
2316 for (request = all_requests; request; request = request->next)
2318 if (request->terminate != browse_termination_callback) continue; // Not a browse operation
2319 if (!request->u.browser.default_domain) continue; // Not an auto-browse operation
2320 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
2322 browser_t **ptr = &request->u.browser.browsers;
2323 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
2324 if (add)
2326 // If we don't already have this domain in our list for this browse operation, add it now
2327 if (!*ptr) add_domain_to_browser(request, &d->name);
2328 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
2330 else
2332 if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
2333 else
2335 DNameListElem *p;
2336 for (p = AutoBrowseDomains; p; p=p->next)
2337 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
2338 if (SameDomainName(&d->name, &p->name)) break;
2339 if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
2340 else
2342 browser_t *rem = *ptr;
2343 *ptr = (*ptr)->next;
2344 mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
2345 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
2353 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
2355 (void)m; // unused
2356 if (result == mStatus_MemFree)
2358 // On shutdown, mDNS_Close automatically deregisters all records
2359 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2360 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2361 // (This should actually no longer be necessary, now that we do the proper cleanup in
2362 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2363 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2364 ARListElem **ptr = &LocalDomainEnumRecords;
2365 while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
2366 if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
2367 mDNSPlatformMemFree(rr->RecordContext);
2371 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2372 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2373 // We may want to turn the common code into a subroutine.
2375 mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2377 // allocate/register legacy and non-legacy _browse PTR record
2378 mStatus err;
2379 ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
2381 debugf("Incrementing %s refcount for %##s",
2382 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2383 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2384 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2386 mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
2387 MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
2388 AppendDNSNameString (&ptr->ar.namestorage, "local");
2389 AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
2390 err = mDNS_Register(m, &ptr->ar);
2391 if (err)
2393 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
2394 mDNSPlatformMemFree(ptr);
2396 else
2398 ptr->next = LocalDomainEnumRecords;
2399 LocalDomainEnumRecords = ptr;
2403 mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2405 ARListElem **ptr = &LocalDomainEnumRecords;
2406 domainname lhs; // left-hand side of PTR, for comparison
2408 debugf("Decrementing %s refcount for %##s",
2409 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2410 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2411 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2413 MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
2414 AppendDNSNameString (&lhs, "local");
2416 while (*ptr)
2418 if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
2420 ARListElem *rem = *ptr;
2421 *ptr = (*ptr)->next;
2422 mDNS_Deregister(m, &rem->ar);
2423 return;
2425 else ptr = &(*ptr)->next;
2429 mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2431 DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
2432 if (!new) { LogMsg("ERROR: malloc"); return; }
2433 AssignDomainName(&new->name, name);
2434 new->uid = uid;
2435 new->next = AutoBrowseDomains;
2436 AutoBrowseDomains = new;
2437 udsserver_automatic_browse_domain_changed(new, mDNStrue);
2440 mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2442 DNameListElem **p = &AutoBrowseDomains;
2443 while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
2444 if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
2445 else
2447 DNameListElem *ptr = *p;
2448 *p = ptr->next;
2449 udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
2450 mDNSPlatformMemFree(ptr);
2454 mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
2456 DNameListElem *d;
2457 for (d = browseDomains; d; d = d->next)
2459 if (add)
2461 RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2462 AddAutoBrowseDomain(d->uid, &d->name);
2464 else
2466 DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2467 RmvAutoBrowseDomain(d->uid, &d->name);
2472 #if APPLE_OSX_mDNSResponder
2474 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2476 int num_autoname = 0;
2477 request_state *req;
2479 // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2480 for (req = all_requests; req; req = req->next)
2482 if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname && req->interfaceIndex != kDNSServiceInterfaceIndexLocalOnly)
2483 num_autoname++;
2486 // If DeviceInfo record is currently registered, see if we need to deregister it
2487 if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
2488 if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
2490 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
2491 mDNS_Deregister(m, &m->DeviceInfo);
2494 // If DeviceInfo record is not currently registered, see if we need to register it
2495 if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
2496 if (num_autoname > 0)
2498 mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
2499 ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
2500 m->DeviceInfo.resrec.rdlength = initializeDeviceInfoTXT(m, m->DeviceInfo.resrec.rdata->u.data);
2501 LogOperation("UpdateDeviceInfoRecord Register %##s", m->DeviceInfo.resrec.name);
2502 mDNS_Register(m, &m->DeviceInfo);
2505 #else // APPLE_OSX_mDNSResponder
2506 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2508 (void)m; // unused
2510 #endif // APPLE_OSX_mDNSResponder
2512 mDNSexport void udsserver_handle_configchange(mDNS *const m)
2514 request_state *req;
2515 service_instance *ptr;
2516 DNameListElem *RegDomains = NULL;
2517 DNameListElem *BrowseDomains = NULL;
2518 DNameListElem *p;
2520 UpdateDeviceInfoRecord(m);
2522 // For autoname services, see if the default service name has changed, necessitating an automatic update
2523 for (req = all_requests; req; req = req->next)
2524 if (req->terminate == regservice_termination_callback)
2525 if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
2527 req->u.servicereg.name = m->nicelabel;
2528 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
2530 ptr->renameonmemfree = 1;
2531 if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
2532 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
2533 if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
2534 regservice_callback(m, &ptr->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
2538 // Let the platform layer get the current DNS information
2539 mDNS_Lock(m);
2540 mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains, mDNSfalse);
2541 mDNS_Unlock(m);
2543 // Any automatic registration domains are also implicitly automatic browsing domains
2544 if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue); // Add the new list first
2545 if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse); // Then clear the old list
2547 // Add any new domains not already in our AutoRegistrationDomains list
2548 for (p=RegDomains; p; p=p->next)
2550 DNameListElem **pp = &AutoRegistrationDomains;
2551 while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
2552 if (!*pp) // If not found in our existing list, this is a new default registration domain
2554 RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
2555 udsserver_default_reg_domain_changed(p, mDNStrue);
2557 else // else found same domainname in both old and new lists, so no change, just delete old copy
2559 DNameListElem *del = *pp;
2560 *pp = (*pp)->next;
2561 mDNSPlatformMemFree(del);
2565 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2566 while (AutoRegistrationDomains)
2568 DNameListElem *del = AutoRegistrationDomains;
2569 AutoRegistrationDomains = AutoRegistrationDomains->next; // Cut record from list FIRST,
2570 DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
2571 udsserver_default_reg_domain_changed(del, mDNSfalse); // before calling udsserver_default_reg_domain_changed()
2572 mDNSPlatformMemFree(del);
2575 // Now we have our new updated automatic registration domain list
2576 AutoRegistrationDomains = RegDomains;
2578 // Add new browse domains to internal list
2579 if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
2581 // Remove old browse domains from internal list
2582 if (SCPrefBrowseDomains)
2584 SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
2585 while (SCPrefBrowseDomains)
2587 DNameListElem *fptr = SCPrefBrowseDomains;
2588 SCPrefBrowseDomains = SCPrefBrowseDomains->next;
2589 mDNSPlatformMemFree(fptr);
2593 // Replace the old browse domains array with the new array
2594 SCPrefBrowseDomains = BrowseDomains;
2597 mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
2599 (void)m; // unused;
2600 (void)q; // unused
2602 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2603 AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
2605 if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
2606 else RmvAutoBrowseDomain(0, &answer->rdata->u.name);
2609 mDNSlocal mStatus handle_browse_request(request_state *request)
2611 char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2612 domainname typedn, d, temp;
2613 mDNSs32 NumSubTypes;
2614 char *AnonData = mDNSNULL;
2615 mStatus err = mStatus_NoError;
2616 int AnonDataLen;
2618 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2619 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2620 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2622 // The browse is scoped to a specific interface index, but the
2623 // interface is not currently in our list.
2624 if (interfaceIndex && !InterfaceID)
2626 // If it's one of the specially defined inteface index values, just return an error.
2627 if (PreDefinedInterfaceIndex(interfaceIndex))
2629 LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex);
2630 return(mStatus_BadParamErr);
2633 // Otherwise, use the specified interface index value and the browse will
2634 // be applied to that interface when it comes up.
2635 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2636 LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex);
2639 if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2640 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
2642 if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2644 request->flags = flags;
2645 request->interfaceIndex = interfaceIndex;
2646 typedn.c[0] = 0;
2647 NumSubTypes = ChopSubTypes(regtype, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
2648 if (NumSubTypes < 0 || NumSubTypes > 1)
2649 return(mStatus_BadParamErr);
2650 AnonDataLen = 0;
2651 if (AnonData)
2653 AnonDataLen = strlen(AnonData);
2654 if (AnonDataLen > MAX_ANONYMOUS_DATA)
2656 LogMsg("handle_browse_request: AnonDataLen %d", AnonDataLen);
2657 return(mStatus_BadParamErr);
2659 // Account for the null byte
2660 AnonDataLen += 1;
2662 if (NumSubTypes == 1)
2664 if (!AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1 + AnonDataLen))
2665 return(mStatus_BadParamErr);
2668 if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
2670 if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
2671 // For over-long service types, we only allow domain "local"
2672 if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrCopy(domain, "local.");
2674 // Set up browser info
2675 request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
2676 request->u.browser.interface_id = InterfaceID;
2677 AssignDomainName(&request->u.browser.regtype, &typedn);
2678 request->u.browser.default_domain = !domain[0];
2679 request->u.browser.browsers = NULL;
2681 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START PID[%d](%s)",
2682 request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain, request->process_id, request->pid_name);
2684 if (request->u.browser.default_domain)
2686 // Start the domain enumeration queries to discover the WAB browse domains
2687 LogInfo("%3d: DNSServiceBrowse Start WAB PID[%d](%s)", request->sd, request->process_id, request->pid_name);
2688 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2690 request->u.browser.AnonData = mDNSNULL;
2691 if (AnonData)
2693 int len = strlen(AnonData) + 1;
2694 request->u.browser.AnonData = mallocL("Anonymous", len);
2695 if (!request->u.browser.AnonData)
2696 return mStatus_NoMemoryErr;
2697 else
2698 mDNSPlatformMemCopy((void *)request->u.browser.AnonData, AnonData, len);
2700 // We need to unconditionally set request->terminate, because even if we didn't successfully
2701 // start any browses right now, subsequent configuration changes may cause successful
2702 // browses to be added, and we'll need to cancel them before freeing this memory.
2703 request->terminate = browse_termination_callback;
2705 if (domain[0])
2707 if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
2708 err = add_domain_to_browser(request, &d);
2710 else
2712 DNameListElem *sdom;
2713 for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
2714 if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
2716 err = add_domain_to_browser(request, &sdom->name);
2717 if (err)
2719 if (SameDomainName(&sdom->name, &localdomain)) break;
2720 else err = mStatus_NoError; // suppress errors for non-local "default" domains
2725 return(err);
2728 // ***************************************************************************
2729 #if COMPILER_LIKES_PRAGMA_MARK
2730 #pragma mark -
2731 #pragma mark - DNSServiceResolve
2732 #endif
2734 mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2736 size_t len = 0;
2737 char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME];
2738 char *data;
2739 reply_state *rep;
2740 request_state *req = question->QuestionContext;
2741 (void)m; // Unused
2743 LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req->sd, question->qname.c, AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
2745 if (!AddRecord)
2747 if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
2748 if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
2749 return;
2752 if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
2753 if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
2755 if (!req->u.resolve.txt || !req->u.resolve.srv) return; // only deliver result to client if we have both answers
2757 ConvertDomainNameToCString(answer->name, fullname);
2758 ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
2760 // calculate reply length
2761 len += sizeof(DNSServiceFlags);
2762 len += sizeof(mDNSu32); // interface index
2763 len += sizeof(DNSServiceErrorType);
2764 len += strlen(fullname) + 1;
2765 len += strlen(target) + 1;
2766 len += 2 * sizeof(mDNSu16); // port, txtLen
2767 len += req->u.resolve.txt->rdlength;
2769 // allocate/init reply header
2770 rep = create_reply(resolve_reply_op, len, req);
2771 rep->rhdr->flags = dnssd_htonl(0);
2772 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
2773 rep->rhdr->error = dnssd_htonl(kDNSServiceErr_NoError);
2775 data = (char *)&rep->rhdr[1];
2777 // write reply data to message
2778 put_string(fullname, &data);
2779 put_string(target, &data);
2780 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[0];
2781 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[1];
2782 put_uint16(req->u.resolve.txt->rdlength, &data);
2783 put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
2785 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
2786 append_reply(req, rep);
2789 mDNSlocal void resolve_termination_callback(request_state *request)
2791 LogOperation("%3d: DNSServiceResolve(%##s) STOP PID[%d](%s)", request->sd, request->u.resolve.qtxt.qname.c, request->process_id, request->pid_name);
2792 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
2793 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2794 LogMcastQ(&mDNSStorage, &request->u.resolve.qsrv, request, q_stop);
2795 if (request->u.resolve.external_advertise)
2796 external_stop_resolving_service(request->u.resolve.qsrv.InterfaceID, &request->u.resolve.qsrv.qname, request->flags);
2799 mDNSlocal mStatus handle_resolve_request(request_state *request)
2801 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2802 domainname fqdn;
2803 mStatus err;
2805 // extract the data from the message
2806 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2807 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2808 mDNSInterfaceID InterfaceID;
2810 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2811 // flag set so that the resolve will run over P2P interfaces that are not yet created.
2812 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
2814 LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2815 flags |= kDNSServiceFlagsIncludeP2P;
2816 interfaceIndex = kDNSServiceInterfaceIndexAny;
2819 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2821 // The operation is scoped to a specific interface index, but the
2822 // interface is not currently in our list.
2823 if (interfaceIndex && !InterfaceID)
2825 // If it's one of the specially defined inteface index values, just return an error.
2826 if (PreDefinedInterfaceIndex(interfaceIndex))
2828 LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex);
2829 return(mStatus_BadParamErr);
2832 // Otherwise, use the specified interface index value and the operation will
2833 // be applied to that interface when it comes up.
2834 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2835 LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex);
2838 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
2839 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2840 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
2841 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2843 if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2845 if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
2846 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
2848 mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
2850 request->flags = flags;
2851 request->interfaceIndex = interfaceIndex;
2853 // format questions
2854 request->u.resolve.qsrv.InterfaceID = InterfaceID;
2855 request->u.resolve.qsrv.flags = flags;
2856 request->u.resolve.qsrv.Target = zeroAddr;
2857 AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
2858 request->u.resolve.qsrv.qtype = kDNSType_SRV;
2859 request->u.resolve.qsrv.qclass = kDNSClass_IN;
2860 request->u.resolve.qsrv.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2861 request->u.resolve.qsrv.ExpectUnique = mDNStrue;
2862 request->u.resolve.qsrv.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2863 request->u.resolve.qsrv.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2864 request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
2865 request->u.resolve.qsrv.DenyOnCellInterface = mDNSfalse;
2866 request->u.resolve.qsrv.DenyOnExpInterface = mDNSfalse;
2867 request->u.resolve.qsrv.SearchListIndex = 0;
2868 request->u.resolve.qsrv.AppendSearchDomains = 0;
2869 request->u.resolve.qsrv.RetryWithSearchDomains = mDNSfalse;
2870 request->u.resolve.qsrv.TimeoutQuestion = 0;
2871 request->u.resolve.qsrv.WakeOnResolve = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
2872 request->u.resolve.qsrv.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2873 request->u.resolve.qsrv.ValidationRequired = 0;
2874 request->u.resolve.qsrv.ValidatingResponse = 0;
2875 request->u.resolve.qsrv.ProxyQuestion = 0;
2876 request->u.resolve.qsrv.qnameOrig = mDNSNULL;
2877 request->u.resolve.qsrv.AnonInfo = mDNSNULL;
2878 request->u.resolve.qsrv.pid = request->process_id;
2879 request->u.resolve.qsrv.euid = request->uid;
2880 request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
2881 request->u.resolve.qsrv.QuestionContext = request;
2883 request->u.resolve.qtxt.InterfaceID = InterfaceID;
2884 request->u.resolve.qtxt.flags = flags;
2885 request->u.resolve.qtxt.Target = zeroAddr;
2886 AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn);
2887 request->u.resolve.qtxt.qtype = kDNSType_TXT;
2888 request->u.resolve.qtxt.qclass = kDNSClass_IN;
2889 request->u.resolve.qtxt.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2890 request->u.resolve.qtxt.ExpectUnique = mDNStrue;
2891 request->u.resolve.qtxt.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2892 request->u.resolve.qtxt.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2893 request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
2894 request->u.resolve.qtxt.DenyOnCellInterface = mDNSfalse;
2895 request->u.resolve.qtxt.DenyOnExpInterface = mDNSfalse;
2896 request->u.resolve.qtxt.SearchListIndex = 0;
2897 request->u.resolve.qtxt.AppendSearchDomains = 0;
2898 request->u.resolve.qtxt.RetryWithSearchDomains = mDNSfalse;
2899 request->u.resolve.qtxt.TimeoutQuestion = 0;
2900 request->u.resolve.qtxt.WakeOnResolve = 0;
2901 request->u.resolve.qtxt.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2902 request->u.resolve.qtxt.ValidationRequired = 0;
2903 request->u.resolve.qtxt.ValidatingResponse = 0;
2904 request->u.resolve.qtxt.ProxyQuestion = 0;
2905 request->u.resolve.qtxt.qnameOrig = mDNSNULL;
2906 request->u.resolve.qtxt.AnonInfo = mDNSNULL;
2907 request->u.resolve.qtxt.pid = request->process_id;
2908 request->u.resolve.qtxt.euid = request->uid;
2909 request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
2910 request->u.resolve.qtxt.QuestionContext = request;
2912 request->u.resolve.ReportTime = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
2914 request->u.resolve.external_advertise = mDNSfalse;
2916 #if 0
2917 if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains)) return(mStatus_NoError);
2918 #endif
2920 // ask the questions
2921 LogOperation("%3d: DNSServiceResolve(%X %d %##s) START PID[%d](%s)", request->sd, flags, interfaceIndex,
2922 request->u.resolve.qsrv.qname.c, request->process_id, request->pid_name);
2923 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);
2925 if (!err)
2927 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
2928 if (err)
2930 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2932 else
2934 request->terminate = resolve_termination_callback;
2935 LogMcastQ(&mDNSStorage, &request->u.resolve.qsrv, request, q_start);
2936 if (callExternalHelpers(InterfaceID, &fqdn, flags))
2938 request->u.resolve.external_advertise = mDNStrue;
2939 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2940 external_start_resolving_service(InterfaceID, &fqdn, flags);
2945 return(err);
2948 // ***************************************************************************
2949 #if COMPILER_LIKES_PRAGMA_MARK
2950 #pragma mark -
2951 #pragma mark - DNSServiceQueryRecord
2952 #endif
2954 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2955 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2956 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2957 // the mDNSCore operation if the client dies or closes its socket.
2959 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2960 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2961 // Returns 0 when there are no more search domains and the caller should reissue the query
2962 mDNSlocal int AppendNewSearchDomain(mDNS *const m, DNSQuestion *question)
2964 domainname *sd;
2965 mStatus err;
2967 // Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2968 // the domains and should try the single label query directly on the wire.
2969 if (question->SearchListIndex == -1)
2971 LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question->qname.c, DNSTypeName(question->qtype));
2972 return -1;
2975 if (!question->AppendSearchDomains)
2977 LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question->qname.c, DNSTypeName(question->qtype));
2978 return -1;
2981 // Save the original name, before we modify them below.
2982 if (!question->qnameOrig)
2984 question->qnameOrig = mallocL("AppendNewSearchDomain", sizeof(domainname));
2985 if (!question->qnameOrig) { LogMsg("AppendNewSearchDomain: ERROR!! malloc failure"); return -1; }
2986 question->qnameOrig->c[0] = 0;
2987 AssignDomainName(question->qnameOrig, &question->qname);
2988 LogInfo("AppendSearchDomain: qnameOrig %##s", question->qnameOrig->c);
2991 sd = uDNS_GetNextSearchDomain(m, question->InterfaceID, &question->SearchListIndex, !question->AppendLocalSearchDomains);
2992 // We use -1 to indicate that we have searched all the domains and should try the single label
2993 // query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2994 if (question->SearchListIndex == -1)
2996 LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2997 return -1;
3000 // Not a common case. Perhaps, we should try the next search domain if it exceeds ?
3001 if (sd && (DomainNameLength(question->qnameOrig) + DomainNameLength(sd)) > MAX_DOMAIN_NAME)
3003 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));
3004 return -1;
3007 // if there are no more search domains and we have already tried this question
3008 // without appending search domains, then we are done.
3009 if (!sd && !ApplySearchDomainsFirst(question))
3011 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question->qname.c, DNSTypeName(question->qtype));
3012 return -1;
3015 // Stop the question before changing the name as negative cache entries could be pointing at this question.
3016 // Even if we don't change the question in the case of returning 0, the caller is going to restart the
3017 // question.
3018 err = mDNS_StopQuery(&mDNSStorage, question);
3019 if (err) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question->qname.c, DNSTypeName(question->qtype), (int)err); }
3021 AssignDomainName(&question->qname, question->qnameOrig);
3022 if (sd)
3024 AppendDomainName(&question->qname, sd);
3025 LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question->qname.c, question->SearchListIndex);
3026 return 1;
3029 // Try the question as single label
3030 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question->qname.c, DNSTypeName(question->qtype));
3031 return 0;
3034 #if APPLE_OSX_mDNSResponder
3036 mDNSlocal mDNSBool DomainInSearchList(const domainname *domain, mDNSBool excludeLocal)
3038 const SearchListElem *s;
3039 int qcount, scount;
3041 qcount = CountLabels(domain);
3042 for (s=SearchList; s; s=s->next)
3044 if (excludeLocal && SameDomainName(&s->domain, &localdomain))
3045 continue;
3046 scount = CountLabels(&s->domain);
3047 if (qcount >= scount)
3049 // Note: When qcount == scount, we do a complete match of the domain
3050 // which is expected by the callers.
3051 const domainname *d = SkipLeadingLabels(domain, (qcount - scount));
3052 if (SameDomainName(&s->domain, d))
3054 return mDNStrue;
3058 return mDNSfalse;
3061 // The caller already checks that this is a dotlocal question.
3062 mDNSlocal mDNSBool ShouldDeliverNegativeResponse(mDNS *const m, DNSQuestion *question)
3064 mDNSu16 qtype;
3066 // If the question matches the search domain exactly or the search domain is a
3067 // subdomain of the question, it is most likely a valid unicast domain and hence
3068 // don't suppress negative responses.
3070 // If the user has configured ".local" as a search domain, we don't want
3071 // to deliver a negative response for names ending in ".local" as that would
3072 // prevent bonjour discovery. Passing mDNStrue for the last argument excludes
3073 // ".local" search domains.
3074 if (DomainInSearchList(&question->qname, mDNStrue))
3076 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) in SearchList", question->qname.c, DNSTypeName(question->qtype));
3077 return mDNStrue;
3080 // Deliver negative response for A/AAAA if there was a positive response for AAAA/A respectively.
3081 if (question->qtype != kDNSType_A && question->qtype != kDNSType_AAAA)
3083 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) not answering local question with negative unicast response",
3084 question->qname.c, DNSTypeName(question->qtype));
3085 return mDNSfalse;
3087 qtype = (question->qtype == kDNSType_A ? kDNSType_AAAA : kDNSType_A);
3088 if (!mDNS_CheckForCacheRecord(m, question, qtype))
3090 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) not answering local question with negative unicast response"
3091 " (can't find positive record)", question->qname.c, DNSTypeName(question->qtype));
3092 return mDNSfalse;
3094 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) answering local with negative unicast response (found positive record)",
3095 question->qname.c, DNSTypeName(question->qtype));
3096 return mDNStrue;
3099 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
3100 // top-level domain
3101 mDNSlocal mStatus SendAdditionalQuery(DNSQuestion *q, request_state *request, mStatus err)
3103 #ifndef UNICAST_DISABLED
3104 extern domainname ActiveDirectoryPrimaryDomain;
3105 DNSQuestion **question2;
3106 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
3107 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
3109 question2 = mDNSNULL;
3110 if (request->hdr.op == query_request)
3111 question2 = &request->u.queryrecord.q2;
3112 else if (request->hdr.op == addrinfo_request)
3114 if (q->qtype == kDNSType_A)
3115 question2 = &request->u.addrinfo.q42;
3116 else if (q->qtype == kDNSType_AAAA)
3117 question2 = &request->u.addrinfo.q62;
3119 if (!question2)
3121 LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3122 return mStatus_BadParamErr;
3125 // Sanity check: If we already sent an additonal query, we don't need to send one more.
3127 // 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
3128 // is called to see whether a unicast query should be sent or not.
3130 // 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
3131 // was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
3132 // send the additional query.
3134 // Thus, it should not be called more than once.
3135 if (*question2)
3137 LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q->qname.c, DNSTypeName(q->qtype));
3138 return err;
3141 if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
3142 if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q))
3144 DNSQuestion *q2;
3145 int labels = CountLabels(&q->qname);
3146 q2 = mallocL("DNSQuestion", sizeof(DNSQuestion));
3147 if (!q2) FatalError("ERROR: SendAdditionalQuery malloc");
3148 *question2 = q2;
3149 *q2 = *q;
3150 q2->InterfaceID = mDNSInterface_Unicast;
3151 q2->ExpectUnique = mDNStrue;
3152 // Always set the QuestionContext to indicate that this question should be stopped
3153 // before freeing. Don't rely on "q".
3154 q2->QuestionContext = request;
3155 // If the query starts as a single label e.g., somehost, and we have search domains with .local,
3156 // queryrecord_result_callback calls this function when .local is appended to "somehost".
3157 // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
3158 // "somehost". We need to copy that information so that when we retry with a different search
3159 // domain e.g., mycompany.local, we get "somehost.mycompany.local".
3160 if (q->qnameOrig)
3162 (*question2)->qnameOrig = mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
3163 if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!! malloc failure"); return mStatus_NoMemoryErr; }
3164 (*question2)->qnameOrig->c[0] = 0;
3165 AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
3166 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
3168 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
3169 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
3170 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
3171 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
3172 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
3173 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
3174 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
3175 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
3176 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
3177 // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
3178 // of those, we don't want do the SOA check for the local
3179 if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname, mDNSfalse))
3181 AssignDomainName(&q2->qname, &localdomain);
3182 q2->qtype = kDNSType_SOA;
3183 q2->LongLived = mDNSfalse;
3184 q2->ForceMCast = mDNSfalse;
3185 q2->ReturnIntermed = mDNStrue;
3186 // Don't append search domains for the .local SOA query
3187 q2->AppendSearchDomains = 0;
3188 q2->AppendLocalSearchDomains = 0;
3189 q2->RetryWithSearchDomains = mDNSfalse;
3190 q2->SearchListIndex = 0;
3191 q2->TimeoutQuestion = 0;
3192 q2->AnonInfo = mDNSNULL;
3193 q2->pid = request->process_id;
3194 q2->euid = request->uid;
3196 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
3197 err = mDNS_StartQuery(&mDNSStorage, q2);
3198 if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
3200 return(err);
3201 #else // !UNICAST_DISABLED
3202 (void) q;
3203 (void) request;
3204 (void) err;
3206 return mStatus_NoError;
3207 #endif // !UNICAST_DISABLED
3209 #endif // APPLE_OSX_mDNSResponder
3211 // This function tries to append a search domain if valid and possible. If so, returns true.
3212 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(mDNS *const m, DNSQuestion *question, request_state *req, QC_result AddRecord)
3214 int result;
3215 // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
3216 // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
3217 // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
3218 // RetryWithSearchDomains which may or may not be set.
3220 // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
3221 // is a valid question for appending search domains, retry by appending domains
3223 if ((AddRecord != QC_suppressed) && question->SearchListIndex != -1 && question->AppendSearchDomains)
3225 question->RetryWithSearchDomains = 0;
3226 result = AppendNewSearchDomain(m, question);
3227 // As long as the result is either zero or 1, we retry the question. If we exahaust the search
3228 // domains (result is zero) we try the original query (as it was before appending the search
3229 // domains) as such on the wire as a last resort if we have not tried them before. For queries
3230 // with more than one label, we have already tried them before appending search domains and
3231 // hence don't retry again
3232 if (result != -1)
3234 mStatus err;
3235 err = mDNS_StartQuery(m, question);
3236 if (!err)
3238 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
3239 // If the result was zero, it meant that there are no search domains and we just retried the question
3240 // as a single label and we should not retry with search domains anymore.
3241 if (!result) question->SearchListIndex = -1;
3242 return mDNStrue;
3244 else
3246 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3247 // We have already stopped the query and could not restart. Reset the appropriate pointers
3248 // so that we don't call stop again when the question terminates
3249 question->QuestionContext = mDNSNULL;
3253 else
3255 LogInfo("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, AddRecord, question->SearchListIndex, question->AppendSearchDomains);
3257 return mDNSfalse;
3260 mDNSlocal void queryrecord_result_reply(mDNS *const m, request_state *req, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord,
3261 DNSServiceErrorType error)
3263 char name[MAX_ESCAPED_DOMAIN_NAME];
3264 size_t len;
3265 DNSServiceFlags flags = 0;
3266 reply_state *rep;
3267 char *data;
3269 ConvertDomainNameToCString(answer->name, name);
3271 LogOperation("%3d: %s(%##s, %s) %s %s", req->sd,
3272 req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
3273 question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
3275 len = sizeof(DNSServiceFlags); // calculate reply data length
3276 len += sizeof(mDNSu32); // interface index
3277 len += sizeof(DNSServiceErrorType);
3278 len += strlen(name) + 1;
3279 len += 3 * sizeof(mDNSu16); // type, class, rdlen
3280 len += answer->rdlength;
3281 len += sizeof(mDNSu32); // TTL
3283 rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
3285 if (AddRecord)
3286 flags |= kDNSServiceFlagsAdd;
3287 if (question->ValidationStatus != 0)
3289 error = kDNSServiceErr_NoError;
3290 if (question->ValidationRequired && question->ValidationState == DNSSECValDone)
3292 switch (question->ValidationStatus) //Set the dnssec flags to be passed on to the Apps here
3294 case DNSSEC_Secure:
3295 flags |= kDNSServiceFlagsSecure;
3296 break;
3297 case DNSSEC_Insecure:
3298 flags |= kDNSServiceFlagsInsecure;
3299 break;
3300 case DNSSEC_Indeterminate:
3301 flags |= kDNSServiceFlagsIndeterminate;
3302 break;
3303 case DNSSEC_Bogus:
3304 flags |= kDNSServiceFlagsBogus;
3305 break;
3306 default:
3307 LogMsg("queryrecord_result_reply unknown status %d for %##s", question->ValidationStatus, question->qname.c);
3312 rep->rhdr->flags = dnssd_htonl(flags);
3313 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
3314 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
3315 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
3316 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
3317 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
3318 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
3319 // should not have existed to answer this question if the corresponding interface is not valid.
3320 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
3321 rep->rhdr->error = dnssd_htonl(error);
3323 data = (char *)&rep->rhdr[1];
3325 put_string(name, &data);
3326 put_uint16(answer->rrtype, &data);
3327 put_uint16(answer->rrclass, &data);
3328 put_uint16(answer->rdlength, &data);
3329 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
3330 // function just does a blind memory copy without regard to structures that may have holes in them.
3331 if (answer->rdlength)
3332 if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
3333 LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
3334 data += answer->rdlength;
3335 put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
3337 append_reply(req, rep);
3338 // Stop the question, if we just timed out
3339 if (error == kDNSServiceErr_Timeout)
3341 mDNS_StopQuery(m, question);
3342 // Reset the pointers so that we don't call stop on termination
3343 question->QuestionContext = mDNSNULL;
3345 else if ((AddRecord == QC_add) && req->hdr.op == addrinfo_request)
3347 // Note: We count all answers including LocalOnly e.g., /etc/hosts. If we
3348 // exclude that, v4ans/v6ans will be zero and we would wrongly think that
3349 // we did not answer questions and setup the status to deliver triggers.
3350 if (question->qtype == kDNSType_A)
3351 req->u.addrinfo.v4ans = 1;
3352 if (question->qtype == kDNSType_AAAA)
3353 req->u.addrinfo.v6ans = 1;
3355 else if ((AddRecord == QC_add) && req->hdr.op == query_request)
3357 if (question->qtype == kDNSType_A || question->qtype == kDNSType_AAAA)
3358 req->u.queryrecord.ans = 1;
3361 #if APPLE_OSX_mDNSResponder
3362 #if !NO_WCF
3363 CHECK_WCF_FUNCTION(WCFIsServerRunning)
3365 struct xucred x;
3366 socklen_t xucredlen = sizeof(x);
3368 if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
3370 if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
3371 (x.cr_version == XUCRED_VERSION))
3373 struct sockaddr_storage addr;
3374 addr.ss_len = 0;
3375 if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
3377 if (answer->rrtype == kDNSType_A)
3379 struct sockaddr_in *const sin = (struct sockaddr_in *)&addr;
3380 sin->sin_port = 0;
3381 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3382 // sin->sin_addr.s_addr = answer->rdata->u.ipv4.NotAnInteger;
3383 if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(mDNSv4Addr)), answer))
3384 LogMsg("queryrecord_result_reply: WCF AF_INET putRData failed");
3385 else
3387 addr.ss_len = sizeof (struct sockaddr_in);
3388 addr.ss_family = AF_INET;
3391 else if (answer->rrtype == kDNSType_AAAA)
3393 struct sockaddr_in6 *const sin6 = (struct sockaddr_in6 *)&addr;
3394 sin6->sin6_port = 0;
3395 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3396 // sin6->sin6_addr.__u6_addr.__u6_addr32[0] = answer->rdata->u.ipv6.l[0];
3397 // sin6->sin6_addr.__u6_addr.__u6_addr32[1] = answer->rdata->u.ipv6.l[1];
3398 // sin6->sin6_addr.__u6_addr.__u6_addr32[2] = answer->rdata->u.ipv6.l[2];
3399 // sin6->sin6_addr.__u6_addr.__u6_addr32[3] = answer->rdata->u.ipv6.l[3];
3400 if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(mDNSv6Addr)), answer))
3401 LogMsg("queryrecord_result_reply: WCF AF_INET6 putRData failed");
3402 else
3404 addr.ss_len = sizeof (struct sockaddr_in6);
3405 addr.ss_family = AF_INET6;
3408 if (addr.ss_len)
3410 debugf("queryrecord_result_reply: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
3411 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3413 WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
3417 else if (answer->rrtype == kDNSType_CNAME)
3419 domainname cname;
3420 char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
3421 if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
3422 LogMsg("queryrecord_result_reply: WCF CNAME putRData failed");
3423 else
3425 ConvertDomainNameToCString(&cname, cname_cstr);
3426 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3428 WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
3433 else my_perror("queryrecord_result_reply: ERROR: getsockopt LOCAL_PEERCRED");
3436 #endif
3437 #endif
3440 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
3442 request_state *req = question->QuestionContext;
3443 DNSServiceErrorType error = kDNSServiceErr_NoError;
3444 DNSQuestion *q = mDNSNULL;
3446 #if APPLE_OSX_mDNSResponder
3448 // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
3449 // get any callbacks from the core after this.
3450 if (!req)
3452 LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3453 return;
3455 if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
3456 q = &req->u.queryrecord.q;
3457 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
3458 q = &req->u.addrinfo.q4;
3459 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
3460 q = &req->u.addrinfo.q6;
3462 if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
3464 mStatus err;
3465 domainname *orig = question->qnameOrig;
3467 LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
3468 mDNS_StopQuery(m, question);
3469 question->QuestionContext = mDNSNULL;
3471 // We got a negative response for the SOA record indicating that .local does not exist.
3472 // But we might have other search domains (that does not end in .local) that can be
3473 // appended to this question. In that case, we want to retry the question. Otherwise,
3474 // we don't want to try this question as unicast.
3475 if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
3477 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
3478 return;
3481 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
3483 // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
3484 // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
3485 // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
3486 // SendAdditionalQuery as to how qnameOrig gets initialized.
3487 *question = *q;
3488 question->InterfaceID = mDNSInterface_Unicast;
3489 question->ExpectUnique = mDNStrue;
3490 question->qnameOrig = orig;
3492 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
3494 // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
3495 // Hence, we need to set it explicitly here.
3496 question->QuestionContext = req;
3497 err = mDNS_StartQuery(m, question);
3498 if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3500 // If we got a positive response to local SOA, then try the .local question as unicast
3501 if (answer->RecordType != kDNSRecordTypePacketNegative) return;
3503 // Fall through and get the next search domain. The question is pointing at .local
3504 // and we don't want to try that. Try the next search domain. Don't try with local
3505 // search domains for the unicast question anymore.
3507 // Note: we started the question above which will be stopped immediately (never sent on the wire)
3508 // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
3509 // question has already started.
3510 question->AppendLocalSearchDomains = 0;
3513 if (q && AddRecord && AddRecord != QC_dnssec && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
3515 // If we get a negative response to the unicast query that we sent above, retry after appending search domains
3516 // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
3517 // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
3518 // To keep things simple, we handle unicast ".local" separately here.
3519 LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3520 if (RetryQuestionWithSearchDomains(m, question, req, AddRecord))
3521 return;
3522 if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
3524 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
3525 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
3526 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
3527 // in the list. We leave it disabled so that it does not hit the wire.
3528 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3529 question->ThisQInterval = 0;
3532 // 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
3533 // domains to append for "q2". In all cases, fall through and deliver the response
3535 #endif // APPLE_OSX_mDNSResponder
3537 // If a query is being suppressed for some reason, we don't have to do any other
3538 // processing.
3540 // Note: We don't check for "SuppressQuery" and instead use QC_suppressed because
3541 // the "core" needs to temporarily turn off SuppressQuery to answer this query.
3542 if (AddRecord == QC_suppressed)
3544 LogInfo("queryrecord_result_callback: Suppressed question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3545 queryrecord_result_reply(m, req, question, answer, AddRecord, kDNSServiceErr_NoSuchRecord);
3546 return;
3549 if (answer->RecordType == kDNSRecordTypePacketNegative)
3551 // If this question needs to be timed out and we have reached the stop time, mark
3552 // the error as timeout. It is possible that we might get a negative response from an
3553 // external DNS server at the same time when this question reaches its stop time. We
3554 // can't tell the difference as there is no indication in the callback. This should
3555 // be okay as we will be timing out this query anyway.
3556 mDNS_Lock(m);
3557 if (question->TimeoutQuestion)
3559 if ((m->timenow - question->StopTime) >= 0)
3561 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3562 error = kDNSServiceErr_Timeout;
3565 mDNS_Unlock(m);
3566 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
3567 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
3568 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
3569 // server is going to assert that pretty much every single multicast name doesn't exist.
3571 // If we are timing out this query, we need to deliver the negative answer to the application
3572 if (error != kDNSServiceErr_Timeout)
3574 if (!answer->InterfaceID && IsLocalDomain(answer->name))
3576 // Sanity check: "q" will be set only if "question" is the .local unicast query.
3577 if (!q)
3579 LogMsg("queryrecord_result_callback: ERROR!! answering multicast question %s with unicast cache record",
3580 RRDisplayString(m, answer));
3581 return;
3583 #if APPLE_OSX_mDNSResponder
3584 if (!ShouldDeliverNegativeResponse(m, question))
3586 return;
3588 #endif // APPLE_OSX_mDNSResponder
3589 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with negative unicast response", question->qname.c,
3590 DNSTypeName(question->qtype));
3592 error = kDNSServiceErr_NoSuchRecord;
3595 // If we get a negative answer, try appending search domains. Don't append search domains
3596 // - if we are timing out this question
3597 // - if the negative response was received as a result of a multicast query
3598 // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
3599 // - if this response is forced e.g., dnssec validation result
3600 if (error != kDNSServiceErr_Timeout)
3602 if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord && AddRecord != QC_dnssec)
3604 // If the original question did not end in .local, we did not send an SOA query
3605 // to figure out whether we should send an additional unicast query or not. If we just
3606 // appended .local, we need to see if we need to send an additional query. This should
3607 // normally happen just once because after we append .local, we ignore all negative
3608 // responses for .local above.
3609 LogInfo("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3610 if (RetryQuestionWithSearchDomains(m, question, req, AddRecord))
3612 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
3613 // be anywhere in the search domain list.
3614 #if APPLE_OSX_mDNSResponder
3615 mStatus err = mStatus_NoError;
3616 err = SendAdditionalQuery(question, req, err);
3617 if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
3618 #endif // APPLE_OSX_mDNSResponder
3619 return;
3623 queryrecord_result_reply(m, req, question, answer, AddRecord, error);
3626 mDNSlocal void queryrecord_termination_callback(request_state *request)
3628 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP PID[%d](%s)",
3629 request->sd, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype), request->process_id, request->pid_name);
3630 if (request->u.queryrecord.q.QuestionContext)
3632 mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q); // no need to error check
3633 LogMcastQ(&mDNSStorage, &request->u.queryrecord.q, request, q_stop);
3634 request->u.queryrecord.q.QuestionContext = mDNSNULL;
3636 else
3638 DNSQuestion *question = &request->u.queryrecord.q;
3639 LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3642 if (request->u.queryrecord.q.qnameOrig)
3644 freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
3645 request->u.queryrecord.q.qnameOrig = mDNSNULL;
3648 if (callExternalHelpers(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->flags))
3650 LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
3651 external_stop_browsing_for_service(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->u.queryrecord.q.qtype, request->flags);
3653 if (request->u.queryrecord.q2)
3655 if (request->u.queryrecord.q2->QuestionContext)
3657 LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
3658 mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
3659 LogMcastQ(&mDNSStorage, request->u.queryrecord.q2, request, q_stop);
3661 else
3663 DNSQuestion *question = request->u.queryrecord.q2;
3664 LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3666 if (request->u.queryrecord.q2->qnameOrig)
3668 LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
3669 freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
3670 request->u.queryrecord.q2->qnameOrig = mDNSNULL;
3672 freeL("queryrecord Q2", request->u.queryrecord.q2);
3673 request->u.queryrecord.q2 = mDNSNULL;
3675 #if APPLE_OSX_mDNSResponder
3677 if (request->u.queryrecord.ans)
3679 DNSQuestion *v4q, *v6q;
3680 // If we are receiving poisitive answers, provide the hint to the
3681 // upper layer.
3682 v4q = v6q = mDNSNULL;
3683 if (request->u.queryrecord.q.qtype == kDNSType_A)
3684 v4q = &request->u.queryrecord.q;
3685 else if (request->u.queryrecord.q.qtype == kDNSType_AAAA)
3686 v6q = &request->u.queryrecord.q;
3687 mDNSPlatformTriggerDNSRetry(&mDNSStorage, v4q, v6q);
3690 #endif // APPLE_OSX_mDNSResponder
3693 mDNSlocal void SetQuestionPolicy(DNSQuestion *q, request_state *req)
3695 int i;
3696 q->euid = req->uid;
3697 // The policy is either based on pid or UUID. Pass a zero pid
3698 // to the "core" if the UUID is valid. If we always pass the pid,
3699 // then the "core" needs to determine whether the uuid is valid
3700 // by examining all the 16 bytes at the time of the policy
3701 // check and also when setting the delegate socket option. Also, it
3702 // requires that we zero out the uuid wherever the question is
3703 // initialized to make sure that it is not interpreted as valid.
3704 // To prevent these intrusive changes, just pass a zero pid to indicate
3705 // that pid is not valid when uuid is valid. In future if we need the
3706 // pid in the question, we will reevaluate this strategy.
3707 if (req->validUUID)
3709 for (i = 0; i < UUID_SIZE; i++)
3711 q->uuid[i] = req->uuid[i];
3713 q->pid = 0;
3715 else
3717 q->pid = req->process_id;
3720 //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
3723 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
3725 DNSQuestion *const q = &request->u.queryrecord.q;
3726 char name[256];
3727 mDNSu16 rrtype, rrclass;
3728 mStatus err;
3730 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3731 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3732 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3734 // The request is scoped to a specific interface index, but the
3735 // interface is not currently in our list.
3736 if (interfaceIndex && !InterfaceID)
3738 // If it's one of the specially defined inteface index values, just return an error.
3739 // Also, caller should return an error immediately if lo0 (index 1) is not configured
3740 // into the current active interfaces. See background in Radar 21967160.
3741 if (PreDefinedInterfaceIndex(interfaceIndex) || interfaceIndex == 1)
3743 LogInfo("handle_queryrecord_request: bad interfaceIndex %d", interfaceIndex);
3744 return(mStatus_BadParamErr);
3747 // Otherwise, use the specified interface index value and the request will
3748 // be applied to that interface when it comes up.
3749 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
3750 LogInfo("handle_queryrecord_request: query pending for interface index %d", interfaceIndex);
3753 if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
3754 rrtype = get_uint16(&request->msgptr, request->msgend);
3755 rrclass = get_uint16(&request->msgptr, request->msgend);
3757 if (!request->msgptr)
3758 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3760 request->flags = flags;
3761 request->interfaceIndex = interfaceIndex;
3762 mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
3764 q->InterfaceID = InterfaceID;
3765 q->flags = flags;
3766 q->Target = zeroAddr;
3767 if (!MakeDomainNameFromDNSNameString(&q->qname, name)) return(mStatus_BadParamErr);
3768 #if 0
3769 if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains)) return (mStatus_NoError);
3770 #endif
3771 q->qtype = rrtype;
3772 q->qclass = rrclass;
3773 q->LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
3774 q->ExpectUnique = mDNSfalse;
3775 q->ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
3776 q->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3777 q->SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
3778 q->TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
3779 q->WakeOnResolve = 0;
3780 q->UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
3781 q->DenyOnCellInterface = (flags & kDNSServiceFlagsDenyCellular) != 0;
3782 q->DenyOnExpInterface = (flags & kDNSServiceFlagsDenyExpensive) != 0;
3783 if ((flags & kDNSServiceFlagsValidate) != 0)
3784 q->ValidationRequired = DNSSEC_VALIDATION_SECURE;
3785 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
3786 q->ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
3787 q->ValidatingResponse = 0;
3788 q->ProxyQuestion = 0;
3789 q->AnonInfo = mDNSNULL;
3790 q->QuestionCallback = queryrecord_result_callback;
3791 q->QuestionContext = request;
3792 q->SearchListIndex = 0;
3794 q->DNSSECAuthInfo = mDNSNULL;
3795 q->DAIFreeCallback = mDNSNULL;
3797 //Turn off dnssec validation for local domains and Question Types: RRSIG/ANY(ANY Type is not supported yet)
3798 if ((IsLocalDomain(&q->qname)) || (q->qtype == kDNSServiceType_RRSIG) || (q->qtype == kDNSServiceType_ANY))
3799 q->ValidationRequired = 0;
3801 // Don't append search domains for fully qualified domain names including queries
3802 // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3803 // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3804 // append search domains or not. So, we record that information in AppendSearchDomains.
3806 // We append search domains only for queries that are a single label. If overriden using command line
3807 // argument "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
3808 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
3810 if ((!(q->ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(q->ValidationRequired == DNSSEC_VALIDATION_INSECURE))
3811 && (rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && name[strlen(name) - 1] != '.' &&
3812 (AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3814 q->AppendSearchDomains = 1;
3815 q->AppendLocalSearchDomains = 1;
3817 else
3819 q->AppendSearchDomains = 0;
3820 q->AppendLocalSearchDomains = 0;
3823 // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3824 // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3825 // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3826 // the cache
3827 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3828 q->qnameOrig = mDNSNULL;
3829 SetQuestionPolicy(q, request);
3831 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START PID[%d](%s)",
3832 request->sd, flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype), request->process_id, request->pid_name);
3833 err = mDNS_StartQuery(&mDNSStorage, q);
3835 if (err)
3837 LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3839 else
3841 request->terminate = queryrecord_termination_callback;
3842 LogMcastQ(&mDNSStorage, q, request, q_start);
3843 if (callExternalHelpers(q->InterfaceID, &q->qname, flags))
3845 LogInfo("handle_queryrecord_request: calling external_start_browsing_for_service()");
3846 external_start_browsing_for_service(q->InterfaceID, &q->qname, q->qtype, flags);
3850 #if APPLE_OSX_mDNSResponder
3851 err = SendAdditionalQuery(q, request, err);
3852 #endif // APPLE_OSX_mDNSResponder
3854 return(err);
3857 // ***************************************************************************
3858 #if COMPILER_LIKES_PRAGMA_MARK
3859 #pragma mark -
3860 #pragma mark - DNSServiceEnumerateDomains
3861 #endif
3863 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3864 const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3866 size_t len;
3867 reply_state *reply;
3868 char *data;
3870 len = sizeof(DNSServiceFlags);
3871 len += sizeof(mDNSu32);
3872 len += sizeof(DNSServiceErrorType);
3873 len += strlen(domain) + 1;
3875 reply = create_reply(enumeration_reply_op, len, request);
3876 reply->rhdr->flags = dnssd_htonl(flags);
3877 reply->rhdr->ifi = dnssd_htonl(ifi);
3878 reply->rhdr->error = dnssd_htonl(err);
3879 data = (char *)&reply->rhdr[1];
3880 put_string(domain, &data);
3881 return reply;
3884 mDNSlocal void enum_termination_callback(request_state *request)
3886 // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3887 if (request->u.enumeration.flags & kDNSServiceFlagsRegistrationDomains)
3889 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3890 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3892 else
3894 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3895 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY);
3897 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3898 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3901 mDNSlocal void enum_result_callback(mDNS *const m,
3902 DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3904 char domain[MAX_ESCAPED_DOMAIN_NAME];
3905 request_state *request = question->QuestionContext;
3906 DNSServiceFlags flags = 0;
3907 reply_state *reply;
3908 (void)m; // Unused
3910 if (answer->rrtype != kDNSType_PTR) return;
3912 #if 0
3913 if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3914 #endif
3916 // We only return add/remove events for the browse and registration lists
3917 // For the default browse and registration answers, we only give an "ADD" event
3918 if (question == &request->u.enumeration.q_default && !AddRecord) return;
3920 if (AddRecord)
3922 flags |= kDNSServiceFlagsAdd;
3923 if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3926 ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3927 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3928 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3929 // network, so we just pass kDNSServiceInterfaceIndexAny
3930 reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3931 if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3933 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "Add" : "Rmv", domain);
3935 append_reply(request, reply);
3938 mDNSlocal mStatus handle_enum_request(request_state *request)
3940 mStatus err;
3941 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3942 DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3943 mDNS_DomainType t_all = reg ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse;
3944 mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3945 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3946 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3947 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3949 if (!request->msgptr)
3950 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3952 request->flags = flags;
3953 request->interfaceIndex = interfaceIndex;
3955 // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
3956 request->u.enumeration.flags = reg;
3958 // enumeration requires multiple questions, so we must link all the context pointers so that
3959 // necessary context can be reached from the callbacks
3960 request->u.enumeration.q_all.QuestionContext = request;
3961 request->u.enumeration.q_default.QuestionContext = request;
3963 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3964 if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
3966 // make the calls
3967 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
3968 (flags & kDNSServiceFlagsBrowseDomains ) ? "kDNSServiceFlagsBrowseDomains" :
3969 (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3970 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
3971 if (!err)
3973 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
3974 if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3975 else request->terminate = enum_termination_callback;
3977 if (!err)
3979 // Start the domain enumeration queries to discover the WAB Browse/Registration domains
3980 if (reg)
3982 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3983 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3985 else
3987 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3988 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY);
3992 return(err);
3995 // ***************************************************************************
3996 #if COMPILER_LIKES_PRAGMA_MARK
3997 #pragma mark -
3998 #pragma mark - DNSServiceReconfirmRecord & Misc
3999 #endif
4001 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
4003 mStatus status = mStatus_BadParamErr;
4004 AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
4005 if (rr)
4007 status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
4008 LogOperation(
4009 (status == mStatus_NoError) ?
4010 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
4011 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
4012 request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
4013 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse), status);
4014 freeL("AuthRecord/handle_reconfirm_request", rr);
4016 return(status);
4019 #if APPLE_OSX_mDNSResponder
4021 mDNSlocal mStatus handle_release_request(request_state *request)
4023 mStatus err = 0;
4024 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
4025 domainname instance;
4027 // extract the data from the message
4028 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4030 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
4031 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
4032 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
4034 LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
4035 return(mStatus_BadParamErr);
4038 if (!request->msgptr)
4040 LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request->sd);
4041 return(mStatus_BadParamErr);
4044 if (build_domainname_from_strings(&instance, name, regtype, domain) < 0)
4046 LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name, regtype, domain);
4047 return(mStatus_BadParamErr);
4050 LogOperation("%3d: PeerConnectionRelease(%X %##s) START PID[%d](%s)",
4051 request->sd, flags, instance.c, request->process_id, request->pid_name);
4053 external_connection_release(&instance);
4054 return(err);
4057 #else // APPLE_OSX_mDNSResponder
4059 mDNSlocal mStatus handle_release_request(request_state *request)
4061 (void) request;
4062 return mStatus_UnsupportedErr;
4065 #endif // APPLE_OSX_mDNSResponder
4067 mDNSlocal mStatus handle_setdomain_request(request_state *request)
4069 char domainstr[MAX_ESCAPED_DOMAIN_NAME];
4070 domainname domain;
4071 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4072 (void)flags; // Unused
4073 if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
4074 !MakeDomainNameFromDNSNameString(&domain, domainstr))
4075 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4077 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
4078 return(mStatus_NoError);
4081 typedef packedstruct
4083 mStatus err;
4084 mDNSu32 len;
4085 mDNSu32 vers;
4086 } DaemonVersionReply;
4088 mDNSlocal void handle_getproperty_request(request_state *request)
4090 const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
4091 char prop[256];
4092 if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
4094 LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
4095 if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
4097 DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
4098 send_all(request->sd, (const char *)&x, sizeof(x));
4099 return;
4103 // If we didn't recogize the requested property name, return BadParamErr
4104 send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
4107 #ifdef APPLE_OSX_mDNSResponder
4108 // The caller can specify either the pid or the uuid. If the pid is not specified,
4109 // update the effective uuid. Don't overwrite the pid which is used for debugging
4110 // purposes and initialized when the socket is opened.
4111 mDNSlocal void handle_connection_delegate_request(request_state *request)
4113 mDNSs32 pid;
4114 socklen_t len;
4116 len = 0;
4117 pid = get_uint32(&request->msgptr, request->msgend);
4118 #ifdef LOCAL_PEEREPID
4119 if (pid)
4121 len = sizeof(pid);
4122 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &request->process_id, &len) != 0)
4123 return;
4124 // to extract the process name from the pid value
4125 if (proc_pidinfo(request->process_id, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
4126 return;
4127 mDNSPlatformStrCopy(request->pid_name, proc.pbsi_comm);
4128 debugf("handle_connection_delegate_request: process id %d, name %s", request->process_id, request->pid_name);
4130 #endif
4131 #ifdef LOCAL_PEEREUUID
4132 if (!pid)
4134 len = UUID_SIZE;
4135 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREUUID, request->uuid, &len) != 0)
4136 return;
4137 request->validUUID = mDNStrue;
4139 #endif
4141 #else
4142 mDNSlocal void handle_connection_delegate_request(request_state *request)
4144 (void) request;
4146 #endif
4148 typedef packedstruct
4150 mStatus err;
4151 mDNSs32 pid;
4152 } PIDInfo;
4154 mDNSlocal void handle_getpid_request(request_state *request)
4156 const request_state *req;
4157 mDNSs32 pid = -1;
4158 mDNSu16 srcport = get_uint16(&request->msgptr, request->msgend);
4159 const DNSQuestion *q = NULL;
4160 PIDInfo pi;
4162 LogMsg("%3d: DNSServiceGetPID START", request->sd);
4164 for (req = all_requests; req; req=req->next)
4166 if (req->hdr.op == query_request)
4167 q = &req->u.queryrecord.q;
4168 else if (req->hdr.op == addrinfo_request)
4169 q = &req->u.addrinfo.q4;
4170 else if (req->hdr.op == addrinfo_request)
4171 q = &req->u.addrinfo.q6;
4173 if (q && q->LocalSocket != NULL)
4175 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4176 if (port == srcport)
4178 pid = req->process_id;
4179 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s] question %##s", htons(srcport), pid, req->pid_name, q->qname.c);
4180 break;
4184 // If we cannot find in the client requests, look to see if this was
4185 // started by mDNSResponder.
4186 if (pid == -1)
4188 for (q = mDNSStorage.Questions; q; q = q->next)
4190 if (q && q->LocalSocket != NULL)
4192 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4193 if (port == srcport)
4195 #if APPLE_OSX_mDNSResponder
4196 pid = getpid();
4197 #endif // APPLE_OSX_mDNSResponder
4198 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s], question %##s", htons(srcport), pid, "_mDNSResponder", q->qname.c);
4199 break;
4205 pi.err = 0;
4206 pi.pid = pid;
4207 send_all(request->sd, (const char *)&pi, sizeof(PIDInfo));
4208 LogMsg("%3d: DNSServiceGetPID STOP", request->sd);
4211 // ***************************************************************************
4212 #if COMPILER_LIKES_PRAGMA_MARK
4213 #pragma mark -
4214 #pragma mark - DNSServiceNATPortMappingCreate
4215 #endif
4217 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
4219 mDNSlocal void port_mapping_termination_callback(request_state *request)
4221 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](%s)", request->sd,
4222 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4223 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4224 request->process_id, request->pid_name);
4225 mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4228 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
4229 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
4231 request_state *request = (request_state *)n->clientContext;
4232 reply_state *rep;
4233 int replyLen;
4234 char *data;
4236 if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
4238 // calculate reply data length
4239 replyLen = sizeof(DNSServiceFlags);
4240 replyLen += 3 * sizeof(mDNSu32); // if index + addr + ttl
4241 replyLen += sizeof(DNSServiceErrorType);
4242 replyLen += 2 * sizeof(mDNSu16); // Internal Port + External Port
4243 replyLen += sizeof(mDNSu8); // protocol
4245 rep = create_reply(port_mapping_reply_op, replyLen, request);
4247 rep->rhdr->flags = dnssd_htonl(0);
4248 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
4249 rep->rhdr->error = dnssd_htonl(n->Result);
4251 data = (char *)&rep->rhdr[1];
4253 *data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
4254 *data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
4255 *data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
4256 *data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
4257 *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
4258 *data++ = request->u.pm.NATinfo.IntPort.b[0];
4259 *data++ = request->u.pm.NATinfo.IntPort.b[1];
4260 *data++ = request->u.pm.NATinfo.ExternalPort.b[0];
4261 *data++ = request->u.pm.NATinfo.ExternalPort.b[1];
4262 put_uint32(request->u.pm.NATinfo.Lifetime, &data);
4264 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
4265 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4266 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4267 &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
4269 append_reply(request, rep);
4272 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
4274 mDNSu32 ttl = 0;
4275 mStatus err = mStatus_NoError;
4277 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4278 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4279 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4280 mDNSu8 protocol = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
4281 (void)flags; // Unused
4282 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
4283 if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
4284 else
4286 request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
4287 request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
4288 request->u.pm.ReqExt.b[0] = *request->msgptr++;
4289 request->u.pm.ReqExt.b[1] = *request->msgptr++;
4290 ttl = get_uint32(&request->msgptr, request->msgend);
4293 if (!request->msgptr)
4294 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4296 if (protocol == 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
4298 if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
4300 else
4302 if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
4303 if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
4306 request->flags = flags;
4307 request->interfaceIndex = interfaceIndex;
4308 request->u.pm.NATinfo.Protocol = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
4309 // u.pm.NATinfo.IntPort = already set above
4310 request->u.pm.NATinfo.RequestedPort = request->u.pm.ReqExt;
4311 request->u.pm.NATinfo.NATLease = ttl;
4312 request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
4313 request->u.pm.NATinfo.clientContext = request;
4315 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](%s)", request->sd,
4316 protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4317 request->process_id, request->pid_name);
4318 err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4319 if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
4320 else request->terminate = port_mapping_termination_callback;
4322 return(err);
4325 // ***************************************************************************
4326 #if COMPILER_LIKES_PRAGMA_MARK
4327 #pragma mark -
4328 #pragma mark - DNSServiceGetAddrInfo
4329 #endif
4331 mDNSlocal void addrinfo_termination_callback(request_state *request)
4333 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP PID[%d](%s)", request->sd, request->u.addrinfo.q4.qname.c,
4334 request->process_id, request->pid_name);
4336 if (request->u.addrinfo.q4.QuestionContext)
4338 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
4339 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q4, request, q_stop);
4340 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4342 if (request->u.addrinfo.q4.qnameOrig)
4344 freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
4345 request->u.addrinfo.q4.qnameOrig = mDNSNULL;
4347 if (request->u.addrinfo.q42)
4349 if (request->u.addrinfo.q42->QuestionContext)
4351 LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
4352 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
4353 LogMcastQ(&mDNSStorage, request->u.addrinfo.q42, request, q_stop);
4355 if (request->u.addrinfo.q42->qnameOrig)
4357 LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
4358 freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
4359 request->u.addrinfo.q42->qnameOrig = mDNSNULL;
4361 freeL("addrinfo Q42", request->u.addrinfo.q42);
4362 request->u.addrinfo.q42 = mDNSNULL;
4365 if (request->u.addrinfo.q6.QuestionContext)
4367 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4368 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q6, request, q_stop);
4369 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4371 if (request->u.addrinfo.q6.qnameOrig)
4373 freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
4374 request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4376 if (request->u.addrinfo.q62)
4378 if (request->u.addrinfo.q62->QuestionContext)
4380 LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
4381 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
4382 LogMcastQ(&mDNSStorage, request->u.addrinfo.q62, request, q_stop);
4384 if (request->u.addrinfo.q62->qnameOrig)
4386 LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
4387 freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
4388 request->u.addrinfo.q62->qnameOrig = mDNSNULL;
4390 freeL("addrinfo Q62", request->u.addrinfo.q62);
4391 request->u.addrinfo.q62 = mDNSNULL;
4393 #if APPLE_OSX_mDNSResponder
4395 DNSQuestion *v4q, *v6q;
4396 v4q = v6q = mDNSNULL;
4397 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
4399 // If we are not delivering answers, we may be timing out prematurely.
4400 // Note down the current state so that we know to retry when we see a
4401 // valid response again.
4402 if (request->u.addrinfo.q4.TimeoutQuestion && !request->u.addrinfo.v4ans)
4404 mDNSPlatformUpdateDNSStatus(&mDNSStorage, &request->u.addrinfo.q4);
4406 // If we have a v4 answer and if we timed out prematurely before, provide
4407 // a trigger to the upper layer so that it can retry questions if needed.
4408 if (request->u.addrinfo.v4ans)
4409 v4q = &request->u.addrinfo.q4;
4411 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4413 if (request->u.addrinfo.q6.TimeoutQuestion && !request->u.addrinfo.v6ans)
4415 mDNSPlatformUpdateDNSStatus(&mDNSStorage, &request->u.addrinfo.q6);
4417 if (request->u.addrinfo.v6ans)
4418 v6q = &request->u.addrinfo.q6;
4420 mDNSPlatformTriggerDNSRetry(&mDNSStorage, v4q, v6q);
4422 #endif // APPLE_OSX_mDNSResponder
4425 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
4427 char hostname[256];
4428 domainname d;
4429 mStatus err = 0;
4430 mDNSs32 serviceIndex = -1; // default unscoped value for ServiceID is -1
4431 mDNSInterfaceID InterfaceID;
4433 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4435 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4437 if (flags & kDNSServiceFlagsServiceIndex)
4439 // NOTE: kDNSServiceFlagsServiceIndex flag can only be set for DNSServiceGetAddrInfo()
4440 LogInfo("DNSServiceGetAddrInfo: kDNSServiceFlagsServiceIndex is SET by the client");
4441 // if kDNSServiceFlagsServiceIndex is SET,
4442 // interpret the interfaceID as the serviceId and set the interfaceID to 0.
4443 serviceIndex = interfaceIndex;
4444 interfaceIndex = 0;
4447 mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
4449 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4451 // The request is scoped to a specific interface index, but the
4452 // interface is not currently in our list.
4453 if (interfaceIndex && !InterfaceID)
4455 // If it's one of the specially defined inteface index values, just return an error.
4456 if (PreDefinedInterfaceIndex(interfaceIndex))
4458 LogInfo("handle_addrinfo_request: bad interfaceIndex %d", interfaceIndex);
4459 return(mStatus_BadParamErr);
4462 // Otherwise, use the specified interface index value and the registration will
4463 // be applied to that interface when it comes up.
4464 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
4465 LogInfo("handle_addrinfo_request: query pending for interface index %d", interfaceIndex);
4468 request->flags = flags;
4469 request->interfaceIndex = interfaceIndex;
4470 request->u.addrinfo.interface_id = InterfaceID;
4471 request->u.addrinfo.flags = flags;
4472 request->u.addrinfo.protocol = get_uint32(&request->msgptr, request->msgend);
4474 if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
4476 if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
4478 if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4480 if (!MakeDomainNameFromDNSNameString(&d, hostname))
4481 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
4483 #if 0
4484 if (!AuthorizedDomain(request, &d, AutoBrowseDomains)) return (mStatus_NoError);
4485 #endif
4487 if (!request->u.addrinfo.protocol)
4489 flags |= kDNSServiceFlagsSuppressUnusable;
4490 request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
4493 request->u.addrinfo.q4.InterfaceID = request->u.addrinfo.q6.InterfaceID = request->u.addrinfo.interface_id;
4494 request->u.addrinfo.q4.ServiceID = request->u.addrinfo.q6.ServiceID = serviceIndex;
4495 request->u.addrinfo.q4.flags = request->u.addrinfo.q6.flags = flags;
4496 request->u.addrinfo.q4.Target = request->u.addrinfo.q6.Target = zeroAddr;
4497 request->u.addrinfo.q4.qname = request->u.addrinfo.q6.qname = d;
4498 request->u.addrinfo.q4.qclass = request->u.addrinfo.q6.qclass = kDNSServiceClass_IN;
4499 request->u.addrinfo.q4.LongLived = request->u.addrinfo.q6.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
4500 request->u.addrinfo.q4.ExpectUnique = request->u.addrinfo.q6.ExpectUnique = mDNSfalse;
4501 request->u.addrinfo.q4.ForceMCast = request->u.addrinfo.q6.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
4502 request->u.addrinfo.q4.ReturnIntermed = request->u.addrinfo.q6.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
4503 request->u.addrinfo.q4.SuppressUnusable = request->u.addrinfo.q6.SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
4504 request->u.addrinfo.q4.TimeoutQuestion = request->u.addrinfo.q6.TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
4505 request->u.addrinfo.q4.WakeOnResolve = request->u.addrinfo.q6.WakeOnResolve = 0;
4506 request->u.addrinfo.q4.UseBackgroundTrafficClass = request->u.addrinfo.q6.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
4507 request->u.addrinfo.q4.DenyOnCellInterface = request->u.addrinfo.q6.DenyOnCellInterface = (flags & kDNSServiceFlagsDenyCellular) != 0;
4508 request->u.addrinfo.q4.DenyOnExpInterface = request->u.addrinfo.q6.DenyOnExpInterface = (flags & kDNSServiceFlagsDenyExpensive) != 0;
4509 if ((flags & kDNSServiceFlagsValidate) != 0)
4510 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE;
4511 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
4512 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
4513 request->u.addrinfo.q4.ValidatingResponse = request->u.addrinfo.q6.ValidatingResponse = 0;
4514 request->u.addrinfo.q4.ProxyQuestion = request->u.addrinfo.q6.ProxyQuestion = 0;
4515 request->u.addrinfo.q4.qnameOrig = request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4516 request->u.addrinfo.q4.AnonInfo = request->u.addrinfo.q6.AnonInfo = mDNSNULL;
4518 SetQuestionPolicy(&request->u.addrinfo.q4, request);
4519 SetQuestionPolicy(&request->u.addrinfo.q6, request);
4521 request->u.addrinfo.q4.DNSSECAuthInfo = request->u.addrinfo.q6.DNSSECAuthInfo = mDNSNULL;
4522 request->u.addrinfo.q4.DAIFreeCallback = request->u.addrinfo.q6.DAIFreeCallback = mDNSNULL;
4524 //Turn off dnssec validation for local domains
4525 if (IsLocalDomain(&d))
4526 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = 0;
4528 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4530 request->u.addrinfo.q6.qtype = kDNSServiceType_AAAA;
4531 request->u.addrinfo.q6.SearchListIndex = 0;
4532 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set
4533 if ((!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4534 && hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4536 request->u.addrinfo.q6.AppendSearchDomains = 1;
4537 request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
4539 else
4541 request->u.addrinfo.q6.AppendSearchDomains = 0;
4542 request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
4544 request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
4545 request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
4546 request->u.addrinfo.q6.QuestionContext = request;
4547 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
4548 if (err != mStatus_NoError)
4550 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4551 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4553 #if APPLE_OSX_mDNSResponder
4554 err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
4555 #endif // APPLE_OSX_mDNSResponder
4556 if (!err)
4558 request->terminate = addrinfo_termination_callback;
4559 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q6, request, q_start);
4563 if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4))
4565 request->u.addrinfo.q4.qtype = kDNSServiceType_A;
4566 request->u.addrinfo.q4.SearchListIndex = 0;
4568 // We append search domains only for queries that are a single label. If overriden using cmd line arg
4569 // "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
4570 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
4572 if ((!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4573 && hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4575 request->u.addrinfo.q4.AppendSearchDomains = 1;
4576 request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
4578 else
4580 request->u.addrinfo.q4.AppendSearchDomains = 0;
4581 request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
4583 request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
4584 request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
4585 request->u.addrinfo.q4.QuestionContext = request;
4586 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
4587 if (err != mStatus_NoError)
4589 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4590 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4591 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4593 // If we started a query for IPv6, we need to cancel it
4594 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4595 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4598 #if APPLE_OSX_mDNSResponder
4599 err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
4600 #endif // APPLE_OSX_mDNSResponder
4601 if (!err)
4603 request->terminate = addrinfo_termination_callback;
4604 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q4, request, q_start);
4608 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START PID[%d](%s)", request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c, request->process_id, request->pid_name);
4609 return(err);
4612 // ***************************************************************************
4613 #if COMPILER_LIKES_PRAGMA_MARK
4614 #pragma mark -
4615 #pragma mark - Main Request Handler etc.
4616 #endif
4618 mDNSlocal request_state *NewRequest(void)
4620 request_state **p = &all_requests;
4621 while (*p)
4622 p=&(*p)->next;
4623 *p = mallocL("request_state", sizeof(request_state));
4624 if (!*p)
4625 FatalError("ERROR: malloc");
4626 mDNSPlatformMemZero(*p, sizeof(request_state));
4627 return(*p);
4630 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
4631 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
4632 mDNSlocal void read_msg(request_state *req)
4634 if (req->ts == t_terminated || req->ts == t_error)
4635 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
4637 if (req->ts == t_complete) // this must be death or something is wrong
4639 char buf[4]; // dummy for death notification
4640 int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
4641 if (!nread) { req->ts = t_terminated; return; }
4642 if (nread < 0) goto rerror;
4643 LogMsg("%3d: ERROR: read data from a completed request", req->sd);
4644 req->ts = t_error;
4645 return;
4648 if (req->ts != t_morecoming)
4649 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
4651 if (req->hdr_bytes < sizeof(ipc_msg_hdr))
4653 mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
4654 int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
4655 if (nread == 0) { req->ts = t_terminated; return; }
4656 if (nread < 0) goto rerror;
4657 req->hdr_bytes += nread;
4658 if (req->hdr_bytes > sizeof(ipc_msg_hdr))
4659 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
4661 // only read data if header is complete
4662 if (req->hdr_bytes == sizeof(ipc_msg_hdr))
4664 ConvertHeaderBytes(&req->hdr);
4665 if (req->hdr.version != VERSION)
4666 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
4668 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
4669 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
4670 // for other overhead, this means any message above 70kB is definitely bogus.
4671 if (req->hdr.datalen > 70000)
4672 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
4673 req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
4674 if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
4675 req->msgptr = req->msgbuf;
4676 req->msgend = req->msgbuf + req->hdr.datalen;
4677 mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
4681 // If our header is complete, but we're still needing more body data, then try to read it now
4682 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
4683 // Any time we need to get the error return socket we know we'll have at least one data byte
4684 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
4685 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
4687 mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
4688 int nread;
4689 #if !defined(_WIN32)
4690 struct iovec vec = { req->msgbuf + req->data_bytes, nleft }; // Tell recvmsg where we want the bytes put
4691 struct msghdr msg;
4692 struct cmsghdr *cmsg;
4693 char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
4694 msg.msg_name = 0;
4695 msg.msg_namelen = 0;
4696 msg.msg_iov = &vec;
4697 msg.msg_iovlen = 1;
4698 msg.msg_control = cbuf;
4699 msg.msg_controllen = sizeof(cbuf);
4700 msg.msg_flags = 0;
4701 nread = recvmsg(req->sd, &msg, 0);
4702 #else
4703 nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
4704 #endif
4705 if (nread == 0) { req->ts = t_terminated; return; }
4706 if (nread < 0) goto rerror;
4707 req->data_bytes += nread;
4708 if (req->data_bytes > req->hdr.datalen)
4709 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
4710 #if !defined(_WIN32)
4711 cmsg = CMSG_FIRSTHDR(&msg);
4712 #if DEBUG_64BIT_SCM_RIGHTS
4713 LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf), sizeof(cbuf), SOL_SOCKET, SCM_RIGHTS);
4714 LogMsg("%3d: Got %d %d %d %d", req->sd, msg.msg_controllen, cmsg ? cmsg->cmsg_len : -1, cmsg ? cmsg->cmsg_level : -1, cmsg ? cmsg->cmsg_type : -1);
4715 #endif // DEBUG_64BIT_SCM_RIGHTS
4716 if (cmsg && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
4718 #if APPLE_OSX_mDNSResponder
4719 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
4720 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
4721 // and it's convenient to repurpose the existing fd-passing code here for that task
4722 if (req->hdr.op == send_bpf)
4724 dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4725 LogOperation("%3d: Got len %d, BPF %d", req->sd, cmsg->cmsg_len, x);
4726 mDNSPlatformReceiveBPF_fd(&mDNSStorage, x);
4728 else
4729 #endif // APPLE_OSX_mDNSResponder
4730 req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4731 #if DEBUG_64BIT_SCM_RIGHTS
4732 LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
4733 #endif // DEBUG_64BIT_SCM_RIGHTS
4734 if (req->data_bytes < req->hdr.datalen)
4736 LogMsg("%3d: Client(PID [%d](%s)) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
4737 req->sd, req->process_id, req->pid_name, req->errsd, req->data_bytes, req->hdr.datalen);
4738 req->ts = t_error;
4739 return;
4742 #endif
4745 // If our header and data are both complete, see if we need to make our separate error return socket
4746 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
4748 if (req->terminate && req->hdr.op != cancel_request)
4750 dnssd_sockaddr_t cliaddr;
4751 #if defined(USE_TCP_LOOPBACK)
4752 mDNSOpaque16 port;
4753 u_long opt = 1;
4754 port.b[0] = req->msgptr[0];
4755 port.b[1] = req->msgptr[1];
4756 req->msgptr += 2;
4757 cliaddr.sin_family = AF_INET;
4758 cliaddr.sin_port = port.NotAnInteger;
4759 cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4760 #else
4761 char ctrl_path[MAX_CTLPATH];
4762 get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH); // path is first element in message buffer
4763 mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
4764 cliaddr.sun_family = AF_LOCAL;
4765 mDNSPlatformStrCopy(cliaddr.sun_path, ctrl_path);
4766 // If the error return path UDS name is empty string, that tells us
4767 // that this is a new version of the library that's going to pass us
4768 // the error return path socket via sendmsg/recvmsg
4769 if (ctrl_path[0] == 0)
4771 if (req->errsd == req->sd)
4772 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
4773 goto got_errfd;
4775 #endif
4777 req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
4778 if (!dnssd_SocketValid(req->errsd))
4780 my_throttled_perror("ERROR: socket");
4781 req->ts = t_error;
4782 return;
4785 if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
4787 #if !defined(USE_TCP_LOOPBACK)
4788 struct stat sb;
4789 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
4790 req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4791 if (stat(cliaddr.sun_path, &sb) < 0)
4792 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4793 else
4794 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);
4795 #endif
4796 req->ts = t_error;
4797 return;
4800 #if !defined(USE_TCP_LOOPBACK)
4801 got_errfd:
4802 #endif
4803 LogOperation("%3d: Result code socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
4804 #if defined(_WIN32)
4805 if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
4806 #else
4807 if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
4808 #endif
4810 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
4811 req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4812 req->ts = t_error;
4813 return;
4817 req->ts = t_complete;
4820 return;
4822 rerror:
4823 if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
4824 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4825 req->ts = t_error;
4828 #define RecordOrientedOp(X) \
4829 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
4831 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
4832 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
4834 mDNSlocal void request_callback(int fd, short filter, void *info)
4836 mStatus err = 0;
4837 request_state *req = info;
4838 mDNSs32 min_size = sizeof(DNSServiceFlags);
4839 (void)fd; // Unused
4840 (void)filter; // Unused
4842 for (;;)
4844 read_msg(req);
4845 if (req->ts == t_morecoming)
4846 return;
4847 if (req->ts == t_terminated || req->ts == t_error)
4849 AbortUnlinkAndFree(req);
4850 return;
4852 if (req->ts != t_complete)
4854 LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req->ts, req->process_id, req->pid_name);
4855 AbortUnlinkAndFree(req);
4856 return;
4858 if (req->hdr.version != VERSION)
4860 LogMsg("request_callback: ERROR: client IPC version %d incompatible with daemon IPC version %d PID[%d][%s]",
4861 req->hdr.version, VERSION, req->process_id, req->pid_name);
4862 AbortUnlinkAndFree(req);
4863 return;
4866 switch(req->hdr.op) // Interface + other data
4868 case connection_request: min_size = 0; break;
4869 case connection_delegate_request: min_size = 4; /* pid */ break;
4870 case reg_service_request: min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
4871 case add_record_request: min_size += 4 /* type, rdlen */ + 4 /* ttl */; break;
4872 case update_record_request: min_size += 2 /* rdlen */ + 4 /* ttl */; break;
4873 case remove_record_request: break;
4874 case browse_request: min_size += sizeof(mDNSu32) + 2 /* type, domain */; break;
4875 case resolve_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4876 case query_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 4 /* type, class*/; break;
4877 case enumeration_request: min_size += sizeof(mDNSu32); break;
4878 case reg_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
4879 case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */; break;
4880 case setdomain_request: min_size += 1 /* domain */; break;
4881 case getproperty_request: min_size = 2; break;
4882 case getpid_request: min_size = 2; break;
4883 case port_mapping_request: min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
4884 case addrinfo_request: min_size += sizeof(mDNSu32) + 4 /* v4/v6 */ + 1 /* hostname */; break;
4885 case send_bpf: // Same as cancel_request below
4886 case cancel_request: min_size = 0; break;
4887 case release_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4888 default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
4889 req->hdr.op, req->process_id, req->pid_name);
4890 min_size = -1; break;
4893 if ((mDNSs32)req->data_bytes < min_size)
4895 LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
4896 req->data_bytes, req->hdr.op, min_size, req->process_id, req->pid_name);
4897 AbortUnlinkAndFree(req);
4898 return;
4900 if (LightweightOp(req->hdr.op) && !req->terminate)
4902 LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
4903 req->hdr.op, req->process_id, req->pid_name);
4904 AbortUnlinkAndFree(req);
4905 return;
4908 // If req->terminate is already set, this means this operation is sharing an existing connection
4909 if (req->terminate && !LightweightOp(req->hdr.op))
4911 request_state *newreq = NewRequest();
4912 newreq->primary = req;
4913 newreq->sd = req->sd;
4914 newreq->errsd = req->errsd;
4915 newreq->uid = req->uid;
4916 newreq->hdr = req->hdr;
4917 newreq->msgbuf = req->msgbuf;
4918 newreq->msgptr = req->msgptr;
4919 newreq->msgend = req->msgend;
4920 // if the parent request is a delegate connection, copy the
4921 // relevant bits
4922 if (req->validUUID)
4924 int i;
4925 newreq->validUUID = mDNStrue;
4926 for (i = 0; i < UUID_SIZE; i++)
4928 newreq->uuid[i] = req->uuid[i];
4931 else
4933 if (req->process_id)
4935 newreq->process_id = req->process_id;
4937 else
4939 set_peer_pid(newreq);
4942 req = newreq;
4945 // Check if the request wants no asynchronous replies.
4946 if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
4948 // If we're shutting down, don't allow new client requests
4949 // We do allow "cancel" and "getproperty" during shutdown
4950 if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
4952 err = mStatus_ServiceNotRunning;
4954 else
4956 switch(req->hdr.op)
4958 // These are all operations that have their own first-class request_state object
4959 case connection_request:
4960 LogOperation("%3d: DNSServiceCreateConnection START PID[%d](%s)",
4961 req->sd, req->process_id, req->pid_name);
4962 req->terminate = connection_termination;
4963 break;
4964 case connection_delegate_request:
4965 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4966 req->sd, req->process_id, req->pid_name);
4967 req->terminate = connection_termination;
4968 handle_connection_delegate_request(req);
4969 break;
4970 case resolve_request: err = handle_resolve_request (req); break;
4971 case query_request: err = handle_queryrecord_request (req); break;
4972 case browse_request: err = handle_browse_request (req); break;
4973 case reg_service_request: err = handle_regservice_request (req); break;
4974 case enumeration_request: err = handle_enum_request (req); break;
4975 case reconfirm_record_request: err = handle_reconfirm_request (req); break;
4976 case setdomain_request: err = handle_setdomain_request (req); break;
4977 case getproperty_request: handle_getproperty_request (req); break;
4978 case getpid_request: handle_getpid_request (req); break;
4979 case port_mapping_request: err = handle_port_mapping_request(req); break;
4980 case addrinfo_request: err = handle_addrinfo_request (req); break;
4981 case send_bpf: /* Do nothing for send_bpf */ break;
4983 // These are all operations that work with an existing request_state object
4984 case reg_record_request: err = handle_regrecord_request (req); break;
4985 case add_record_request: err = handle_add_request (req); break;
4986 case update_record_request: err = handle_update_request (req); break;
4987 case remove_record_request: err = handle_removerecord_request(req); break;
4988 case cancel_request: handle_cancel_request (req); break;
4989 case release_request: err = handle_release_request (req); break;
4990 default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
4991 req->sd, req->hdr.op, req->process_id, req->pid_name); break;
4994 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
4995 if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
4997 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
4998 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
4999 if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf && req->hdr.op != getpid_request)
5001 const mStatus err_netorder = dnssd_htonl(err);
5002 send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
5003 if (req->errsd != req->sd)
5005 LogOperation("%3d: Result code socket %d closed %08X %08X (%d)",
5006 req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
5007 dnssd_close(req->errsd);
5008 req->errsd = req->sd;
5009 // Also need to reset the parent's errsd, if this is a subordinate operation
5010 if (req->primary) req->primary->errsd = req->primary->sd;
5014 // Reset ready to accept the next req on this pipe
5015 if (req->primary) req = req->primary;
5016 req->ts = t_morecoming;
5017 req->hdr_bytes = 0;
5018 req->data_bytes = 0;
5019 req->msgbuf = mDNSNULL;
5020 req->msgptr = mDNSNULL;
5021 req->msgend = 0;
5025 mDNSlocal void connect_callback(int fd, short filter, void *info)
5027 dnssd_sockaddr_t cliaddr;
5028 dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
5029 dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
5030 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
5031 unsigned long optval = 1;
5032 #endif
5034 (void)filter; // Unused
5035 (void)info; // Unused
5037 if (!dnssd_SocketValid(sd))
5039 if (dnssd_errno != dnssd_EWOULDBLOCK)
5040 my_throttled_perror("ERROR: accept");
5041 return;
5044 #ifdef SO_NOSIGPIPE
5045 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
5046 if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
5047 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
5048 #endif
5050 #if defined(_WIN32)
5051 if (ioctlsocket(sd, FIONBIO, &optval) != 0)
5052 #else
5053 if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
5054 #endif
5056 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
5057 dnssd_close(sd);
5058 return;
5060 else
5062 request_state *request = NewRequest();
5063 request->ts = t_morecoming;
5064 request->sd = sd;
5065 request->errsd = sd;
5066 set_peer_pid(request);
5067 #if APPLE_OSX_mDNSResponder
5068 struct xucred x;
5069 socklen_t xucredlen = sizeof(x);
5070 if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION)
5071 request->uid = x.cr_uid; // save the effective userid of the client
5072 else
5073 my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
5075 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
5076 #endif // APPLE_OSX_mDNSResponder
5077 LogOperation("%3d: connect_callback: Adding FD for uid %u", request->sd, request->uid);
5078 udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
5082 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
5084 #if defined(SO_NP_EXTENSIONS)
5085 struct so_np_extensions sonpx;
5086 socklen_t optlen = sizeof(struct so_np_extensions);
5087 sonpx.npx_flags = SONPX_SETOPTSHUT;
5088 sonpx.npx_mask = SONPX_SETOPTSHUT;
5089 if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
5090 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
5091 #endif
5092 #if defined(_WIN32)
5093 // SEH: do we even need to do this on windows?
5094 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
5095 u_long opt = 1;
5096 if (ioctlsocket(skt, FIONBIO, &opt) != 0)
5097 #else
5098 if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
5099 #endif
5101 my_perror("ERROR: could not set listen socket to non-blocking mode");
5102 return mDNSfalse;
5105 if (listen(skt, LISTENQ) != 0)
5107 my_perror("ERROR: could not listen on listen socket");
5108 return mDNSfalse;
5111 if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
5113 my_perror("ERROR: could not add listen socket to event loop");
5114 return mDNSfalse;
5116 else
5118 LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
5119 mDNSStorage.uds_listener_skt = skt;
5121 return mDNStrue;
5124 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
5126 dnssd_sockaddr_t laddr;
5127 int ret;
5128 mDNSu32 i = 0;
5130 LogInfo("udsserver_init: %d %d", _DNS_SD_H, mDNSStorage.mDNS_plat);
5132 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
5133 if (PID_FILE[0])
5135 FILE *fp = fopen(PID_FILE, "w");
5136 if (fp != NULL)
5138 fprintf(fp, "%d\n", (int)getpid());
5139 fclose(fp);
5143 if (skts)
5145 for (i = 0; i < count; i++)
5146 if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
5147 goto error;
5149 else
5151 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
5152 if (!dnssd_SocketValid(listenfd))
5154 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
5155 goto error;
5158 mDNSPlatformMemZero(&laddr, sizeof(laddr));
5160 #if defined(USE_TCP_LOOPBACK)
5162 laddr.sin_family = AF_INET;
5163 laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
5164 laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
5165 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5166 if (ret < 0)
5168 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5169 goto error;
5172 #else
5174 mode_t mask = umask(0);
5175 unlink(MDNS_UDS_SERVERPATH); // OK if this fails
5176 laddr.sun_family = AF_LOCAL;
5177 #ifndef NOT_HAVE_SA_LEN
5178 // According to Stevens (section 3.2), there is no portable way to
5179 // determine whether sa_len is defined on a particular platform.
5180 laddr.sun_len = sizeof(struct sockaddr_un);
5181 #endif
5182 if (strlen(MDNS_UDS_SERVERPATH) >= sizeof(laddr.sun_path))
5184 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
5185 goto error;
5187 mDNSPlatformStrCopy(laddr.sun_path, MDNS_UDS_SERVERPATH);
5188 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5189 umask(mask);
5190 if (ret < 0)
5192 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5193 goto error;
5196 #endif
5198 if (!uds_socket_setup(listenfd)) goto error;
5201 #if !defined(PLATFORM_NO_RLIMIT)
5203 // Set maximum number of open file descriptors
5204 #define MIN_OPENFILES 10240
5205 struct rlimit maxfds, newfds;
5207 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
5208 // you have to get and set rlimits once before getrlimit will return sensible values
5209 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5210 if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5212 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5213 newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
5214 newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
5215 if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
5216 if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5218 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5219 debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
5220 debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
5222 #endif
5224 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
5225 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
5226 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
5227 mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
5228 mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
5230 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
5231 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
5232 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
5233 AddAutoBrowseDomain(0, &localdomain);
5235 udsserver_handle_configchange(&mDNSStorage);
5236 return 0;
5238 error:
5240 my_perror("ERROR: udsserver_init");
5241 return -1;
5244 mDNSexport int udsserver_exit(void)
5246 // Cancel all outstanding client requests
5247 while (all_requests) AbortUnlinkAndFree(all_requests);
5249 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
5250 // created in udsserver_init, and others we created as a result of reading local configuration data
5251 while (LocalDomainEnumRecords)
5253 ARListElem *rem = LocalDomainEnumRecords;
5254 LocalDomainEnumRecords = LocalDomainEnumRecords->next;
5255 mDNS_Deregister(&mDNSStorage, &rem->ar);
5258 // If the launching environment created no listening socket,
5259 // that means we created it ourselves, so we should clean it up on exit
5260 if (dnssd_SocketValid(listenfd))
5262 dnssd_close(listenfd);
5263 #if !defined(USE_TCP_LOOPBACK)
5264 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
5265 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
5266 // It would be nice if we could find a solution to this problem
5267 if (unlink(MDNS_UDS_SERVERPATH))
5268 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
5269 #endif
5272 if (PID_FILE[0]) unlink(PID_FILE);
5274 return 0;
5277 mDNSlocal void LogClientInfo(mDNS *const m, request_state *req)
5279 char prefix[16];
5280 if (req->primary)
5281 mDNS_snprintf(prefix, sizeof(prefix), " -> ");
5282 else
5283 mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
5285 if (!req->terminate)
5286 LogMsgNoIdent("%s No operation yet on this socket", prefix);
5287 else if (req->terminate == connection_termination)
5289 int num_records = 0, num_ops = 0;
5290 const registered_record_entry *p;
5291 request_state *r;
5292 for (p = req->u.reg_recs; p; p=p->next) num_records++;
5293 for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
5294 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
5295 prefix, num_records, num_records != 1 ? "s" : "", num_ops, num_ops != 1 ? "s" : "",
5296 req->process_id, req->pid_name);
5297 for (p = req->u.reg_recs; p; p=p->next)
5298 LogMsgNoIdent(" -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
5299 req->flags, req->interfaceIndex, p->key, ARDisplayString(m, p->rr), req->process_id, req->pid_name);
5300 for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(m, r);
5302 else if (req->terminate == regservice_termination_callback)
5304 service_instance *ptr;
5305 char anonstr[256];
5306 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5307 LogMsgNoIdent("%s DNSServiceRegister 0x%08X %2d %##s%s %u/%u PID[%d](%s)",
5308 (ptr == req->u.servicereg.instances) ? prefix : " ", req->flags, req->interfaceIndex, ptr->srs.RR_SRV.resrec.name->c,
5309 AnonDataToString(ptr->srs.AnonData, 0, anonstr, sizeof(anonstr)), mDNSVal16(req->u.servicereg.port),
5310 SRS_PORT(&ptr->srs), req->process_id, req->pid_name);
5312 else if (req->terminate == browse_termination_callback)
5314 browser_t *blist;
5315 char anonstr[256];
5316 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5317 LogMsgNoIdent("%s DNSServiceBrowse 0x%08X %2d %##s%s PID[%d](%s)",
5318 (blist == req->u.browser.browsers) ? prefix : " ", req->flags, req->interfaceIndex, blist->q.qname.c,
5319 AnonDataToString(req->u.browser.AnonData, 0, anonstr, sizeof(anonstr)), req->process_id, req->pid_name);
5321 else if (req->terminate == resolve_termination_callback)
5322 LogMsgNoIdent("%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
5323 prefix, req->flags, req->interfaceIndex, req->u.resolve.qsrv.qname.c, req->process_id, req->pid_name);
5324 else if (req->terminate == queryrecord_termination_callback)
5325 LogMsgNoIdent("%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
5326 prefix, req->flags, req->interfaceIndex, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype), req->process_id, req->pid_name);
5327 else if (req->terminate == enum_termination_callback)
5328 LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
5329 prefix, req->flags, req->interfaceIndex, req->u.enumeration.q_all.qname.c, req->process_id, req->pid_name);
5330 else if (req->terminate == port_mapping_termination_callback)
5331 LogMsgNoIdent("%s DNSServiceNATPortMapping 0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
5332 prefix,
5333 req->flags,
5334 req->interfaceIndex,
5335 req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : " ",
5336 req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : " ",
5337 mDNSVal16(req->u.pm.NATinfo.IntPort),
5338 mDNSVal16(req->u.pm.ReqExt),
5339 &req->u.pm.NATinfo.ExternalAddress,
5340 mDNSVal16(req->u.pm.NATinfo.ExternalPort),
5341 req->u.pm.NATinfo.NATLease,
5342 req->u.pm.NATinfo.Lifetime,
5343 req->process_id, req->pid_name);
5344 else if (req->terminate == addrinfo_termination_callback)
5345 LogMsgNoIdent("%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
5346 prefix, req->flags, req->interfaceIndex,
5347 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5348 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5349 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name);
5350 else
5351 LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
5354 mDNSlocal void GetMcastClients(request_state *req)
5356 if (req->terminate == connection_termination)
5358 int num_records = 0, num_ops = 0;
5359 const registered_record_entry *p;
5360 request_state *r;
5361 for (p = req->u.reg_recs; p; p=p->next)
5362 num_records++;
5363 for (r = req->next; r; r=r->next)
5364 if (r->primary == req)
5365 num_ops++;
5366 for (p = req->u.reg_recs; p; p=p->next)
5368 if (!AuthRecord_uDNS(p->rr))
5369 n_mrecords++;
5371 for (r = req->next; r; r=r->next)
5372 if (r->primary == req)
5373 GetMcastClients(r);
5375 else if (req->terminate == regservice_termination_callback)
5377 service_instance *ptr;
5378 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5380 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5381 n_mrecords++;
5384 else if (req->terminate == browse_termination_callback)
5386 browser_t *blist;
5387 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5389 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5390 n_mquests++;
5393 else if (req->terminate == resolve_termination_callback)
5395 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5396 n_mquests++;
5398 else if (req->terminate == queryrecord_termination_callback)
5400 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5401 n_mquests++;
5403 else if (req->terminate == addrinfo_termination_callback)
5405 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5406 n_mquests++;
5408 else
5410 return;
5415 mDNSlocal void LogMcastClientInfo(request_state *req)
5417 if (!req->terminate)
5418 LogMcastNoIdent("No operation yet on this socket");
5419 else if (req->terminate == connection_termination)
5421 int num_records = 0, num_ops = 0;
5422 const registered_record_entry *p;
5423 request_state *r;
5424 for (p = req->u.reg_recs; p; p=p->next)
5425 num_records++;
5426 for (r = req->next; r; r=r->next)
5427 if (r->primary == req)
5428 num_ops++;
5429 for (p = req->u.reg_recs; p; p=p->next)
5431 if (!AuthRecord_uDNS(p->rr))
5432 LogMcastNoIdent("R: -> DNSServiceRegisterRecord: %##s %s PID[%d](%s)", p->rr->resrec.name->c,
5433 DNSTypeName(p->rr->resrec.rrtype), req->process_id, req->pid_name, i_mcount++);
5435 for (r = req->next; r; r=r->next)
5436 if (r->primary == req)
5437 LogMcastClientInfo(r);
5439 else if (req->terminate == regservice_termination_callback)
5441 service_instance *ptr;
5442 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5444 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5445 LogMcastNoIdent("R: DNSServiceRegister: %##s %u/%u PID[%d](%s)", ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port),
5446 SRS_PORT(&ptr->srs), req->process_id, req->pid_name, i_mcount++);
5449 else if (req->terminate == browse_termination_callback)
5451 browser_t *blist;
5452 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5454 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5455 LogMcastNoIdent("Q: DNSServiceBrowse %##s %s PID[%d](%s)", blist->q.qname.c, DNSTypeName(blist->q.qtype),
5456 req->process_id, req->pid_name, i_mcount++);
5459 else if (req->terminate == resolve_termination_callback)
5461 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5462 LogMcastNoIdent("Q: DNSServiceResolve %##s %s PID[%d](%s)", req->u.resolve.qsrv.qname.c, DNSTypeName(req->u.resolve.qsrv.qtype),
5463 req->process_id, req->pid_name, i_mcount++);
5465 else if (req->terminate == queryrecord_termination_callback)
5467 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5468 LogMcastNoIdent("Q: DNSServiceQueryRecord %##s %s PID[%d](%s)", req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype),
5469 req->process_id, req->pid_name, i_mcount++);
5471 else if (req->terminate == addrinfo_termination_callback)
5473 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5474 LogMcastNoIdent("Q: DNSServiceGetAddrInfo %s%s %##s PID[%d](%s)",
5475 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5476 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5477 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name, i_mcount++);
5479 else
5481 return;
5486 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
5488 switch (rtype)
5490 case kDNSRecordTypeUnregistered: return ("Unregistered ");
5491 case kDNSRecordTypeDeregistering: return ("Deregistering");
5492 case kDNSRecordTypeUnique: return ("Unique ");
5493 case kDNSRecordTypeAdvisory: return ("Advisory ");
5494 case kDNSRecordTypeShared: return ("Shared ");
5495 case kDNSRecordTypeVerified: return ("Verified ");
5496 case kDNSRecordTypeKnownUnique: return ("KnownUnique ");
5497 default: return("Unknown");
5501 mDNSlocal void LogEtcHosts(mDNS *const m)
5503 mDNSBool showheader = mDNStrue;
5504 const AuthRecord *ar;
5505 mDNSu32 slot;
5506 AuthGroup *ag;
5507 int count = 0;
5508 int authslot = 0;
5509 mDNSBool truncated = 0;
5511 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5513 if (m->rrauth.rrauth_hash[slot]) authslot++;
5514 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5515 for (ar = ag->members; ar; ar = ar->next)
5517 if (ar->RecordCallback != FreeEtcHosts) continue;
5518 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5520 // Print a maximum of 50 records
5521 if (count++ >= 50) { truncated = mDNStrue; continue; }
5522 if (ar->ARType == AuthRecordLocalOnly)
5524 if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
5525 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5526 else
5528 mDNSu32 scopeid = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
5529 LogMsgNoIdent(" %s %u %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
5535 if (showheader) LogMsgNoIdent("<None>");
5536 else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
5539 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
5541 mDNSBool showheader = mDNStrue;
5542 const AuthRecord *ar;
5543 mDNSu32 slot;
5544 AuthGroup *ag;
5546 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5548 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5549 for (ar = ag->members; ar; ar = ar->next)
5551 if (ar->RecordCallback == FreeEtcHosts) continue;
5552 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5554 // Print a maximum of 400 records
5555 if (ar->ARType == AuthRecordLocalOnly)
5556 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5557 else if (ar->ARType == AuthRecordP2P)
5558 LogMsgNoIdent(" %s PP %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5562 if (showheader) LogMsgNoIdent("<None>");
5565 mDNSlocal char *AnonInfoToString(AnonymousInfo *ai, char *anonstr, int anstrlen)
5567 anonstr[0] = 0;
5568 if (ai && ai->AnonData)
5570 return (AnonDataToString(ai->AnonData, ai->AnonDataLen, anonstr, anstrlen));
5572 return anonstr;
5575 mDNSlocal void LogOneAuthRecord(mDNS *const m, const AuthRecord *ar, mDNSs32 now, const char *const ifname)
5577 char anstr[256];
5578 if (AuthRecord_uDNS(ar))
5580 LogMsgNoIdent("%7d %7d %7d %7d %s %s",
5581 ar->ThisAPInterval / mDNSPlatformOneSecond,
5582 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5583 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5584 ar->state,
5585 ar->AllowRemoteQuery ? "☠" : " ",
5586 ARDisplayString(m, ar));
5588 else
5590 LogMsgNoIdent("%7d %7d %7d %7s %s %s%s",
5591 ar->ThisAPInterval / mDNSPlatformOneSecond,
5592 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5593 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5594 ifname ? ifname : "ALL",
5595 ar->AllowRemoteQuery ? "☠" : " ",
5596 ARDisplayString(m, ar), AnonInfoToString(ar->resrec.AnonInfo, anstr, sizeof(anstr)));
5600 mDNSlocal void LogAuthRecords(mDNS *const m, const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
5602 mDNSBool showheader = mDNStrue;
5603 const AuthRecord *ar;
5604 OwnerOptData owner = zeroOwner;
5605 for (ar = ResourceRecords; ar; ar=ar->next)
5607 const char *const ifname = InterfaceNameForID(m, ar->resrec.InterfaceID);
5608 if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
5610 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" Int Next Expire State"); }
5611 if (proxy) (*proxy)++;
5612 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
5614 owner = ar->WakeUp;
5615 if (owner.password.l[0])
5616 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
5617 else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
5618 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner.HMAC, &owner.IMAC, owner.seq);
5619 else
5620 LogMsgNoIdent("Proxying for %.6a seq %d", &owner.HMAC, owner.seq);
5622 if (AuthRecord_uDNS(ar))
5624 LogOneAuthRecord(m, ar, now, ifname);
5626 else if (ar->ARType == AuthRecordLocalOnly)
5628 LogMsgNoIdent(" LO %s", ARDisplayString(m, ar));
5630 else if (ar->ARType == AuthRecordP2P)
5632 LogMsgNoIdent(" PP %s", ARDisplayString(m, ar));
5634 else
5636 LogOneAuthRecord(m, ar, now, ifname);
5637 if (ar->resrec.AnonInfo)
5639 ResourceRecord *nsec3 = ar->resrec.AnonInfo->nsec3RR;
5640 // We just print the values from the AuthRecord to keep it nicely aligned though
5641 // all we want here is the nsec3 information.
5642 LogMsgNoIdent("%7d %7d %7d %7s %s",
5643 ar->ThisAPInterval / mDNSPlatformOneSecond,
5644 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5645 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5646 ifname ? ifname : "ALL",
5647 RRDisplayString(m, nsec3));
5652 if (showheader) LogMsgNoIdent("<None>");
5655 mDNSlocal void PrintOneCacheRecord(mDNS *const m, const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5657 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5658 slot,
5659 cr->CRActiveQuestion ? "*" : " ",
5660 remain,
5661 ifname ? ifname : "-U-",
5662 (cr->resrec.RecordType == kDNSRecordTypePacketNegative) ? "-" :
5663 (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5664 DNSTypeName(cr->resrec.rrtype),
5665 CRDisplayString(m, cr));
5666 (*CacheUsed)++;
5669 mDNSlocal void PrintCachedRecords(mDNS *const m, const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5671 CacheRecord *nsec;
5672 CacheRecord *soa;
5673 nsec = cr->nsec;
5675 // The records that are cached under the main cache record like nsec, soa don't have
5676 // their own lifetime. If the main cache record expires, they also expire.
5677 while (nsec)
5679 PrintOneCacheRecord(m, nsec, slot, remain, ifname, CacheUsed);
5680 nsec = nsec->next;
5682 soa = cr->soa;
5683 if (soa)
5685 PrintOneCacheRecord(m, soa, slot, remain, ifname, CacheUsed);
5687 if (cr->resrec.AnonInfo)
5689 ResourceRecord *nsec3 = cr->resrec.AnonInfo->nsec3RR;
5690 // Even though it is a resource record, we print the sameway
5691 // as a cache record so that it aligns properly.
5692 if (nsec3)
5694 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5695 slot,
5696 " ",
5697 remain,
5698 ifname ? ifname : "-U-",
5699 (nsec3->RecordType == kDNSRecordTypePacketNegative) ? "-" :
5700 (nsec3->RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5701 DNSTypeName(nsec3->rrtype),
5702 RRDisplayString(m, nsec3));
5707 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen)
5709 adstr[0] = 0;
5710 if (ad)
5712 int len;
5713 char *orig = adstr;
5715 // If the caller is lazy to compute the length, we do it for them.
5716 if (!adlen)
5717 len = strlen((const char *)ad);
5718 else
5719 len = adlen;
5721 // Print the anondata within brackets. Hence, we need space for two
5722 // brackets and a NULL byte.
5723 if (len > (adstrlen - 3))
5724 len = adstrlen - 3;
5726 *adstr++ = '(';
5727 mDNSPlatformMemCopy(adstr, ad, len);
5728 adstr[len] = ')';
5729 adstr[len+1] = 0;
5730 return orig;
5732 return adstr;
5735 mDNSexport void LogMDNSStatistics(mDNS *const m)
5737 LogMsgNoIdent("--- MDNS Statistics ---");
5739 LogMsgNoIdent("Name Conflicts %u", m->mDNSStats.NameConflicts);
5740 LogMsgNoIdent("KnownUnique Name Conflicts %u", m->mDNSStats.KnownUniqueNameConflicts);
5741 LogMsgNoIdent("Duplicate Query Suppressions %u", m->mDNSStats.DupQuerySuppressions);
5742 LogMsgNoIdent("KA Suppressions %u", m->mDNSStats.KnownAnswerSuppressions);
5743 LogMsgNoIdent("KA Multiple Packets %u", m->mDNSStats.KnownAnswerMultiplePkts);
5744 LogMsgNoIdent("Poof Cache Deletions %u", m->mDNSStats.PoofCacheDeletions);
5745 LogMsgNoIdent("--------------------------------");
5747 LogMsgNoIdent("Multicast packets Sent %u", m->MulticastPacketsSent);
5748 LogMsgNoIdent("Multicast packets Received %u", m->MPktNum);
5749 LogMsgNoIdent("Remote Subnet packets %u", m->RemoteSubnet);
5750 LogMsgNoIdent("QU questions received %u", m->mDNSStats.UnicastBitInQueries);
5751 LogMsgNoIdent("Normal multicast questions %u", m->mDNSStats.NormalQueries);
5752 LogMsgNoIdent("Answers for questions %u", m->mDNSStats.MatchingAnswersForQueries);
5753 LogMsgNoIdent("Unicast responses %u", m->mDNSStats.UnicastResponses);
5754 LogMsgNoIdent("Multicast responses %u", m->mDNSStats.MulticastResponses);
5755 LogMsgNoIdent("Unicast response Demotions %u", m->mDNSStats.UnicastDemotedToMulticast);
5756 LogMsgNoIdent("--------------------------------");
5758 LogMsgNoIdent("Sleeps %u", m->mDNSStats.Sleeps);
5759 LogMsgNoIdent("Wakeups %u", m->mDNSStats.Wakes);
5760 LogMsgNoIdent("Interface UP events %u", m->mDNSStats.InterfaceUp);
5761 LogMsgNoIdent("Interface UP Flap events %u", m->mDNSStats.InterfaceUpFlap);
5762 LogMsgNoIdent("Interface Down events %u", m->mDNSStats.InterfaceDown);
5763 LogMsgNoIdent("Interface DownFlap events %u", m->mDNSStats.InterfaceDownFlap);
5764 LogMsgNoIdent("Cache refresh queries %u", m->mDNSStats.CacheRefreshQueries);
5765 LogMsgNoIdent("Cache refreshed %u", m->mDNSStats.CacheRefreshed);
5766 LogMsgNoIdent("Wakeup on Resolves %u", m->mDNSStats.WakeOnResolves);
5769 mDNSexport void udsserver_info(mDNS *const m)
5771 const mDNSs32 now = mDNS_TimeNow(m);
5772 mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
5773 int ProxyA = 0, ProxyD = 0;
5774 const CacheGroup *cg;
5775 const CacheRecord *cr;
5776 const DNSQuestion *q;
5777 const DNameListElem *d;
5778 const SearchListElem *s;
5780 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
5782 LogMsgNoIdent("------------ Cache -------------");
5783 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
5784 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5786 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
5788 CacheUsed++; // Count one cache entity for the CacheGroup object
5789 for (cr = cg->members; cr; cr=cr->next)
5791 const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
5792 const char *ifname;
5793 mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
5794 if (!InterfaceID && cr->resrec.rDNSServer && cr->resrec.rDNSServer->scoped)
5795 InterfaceID = cr->resrec.rDNSServer->interface;
5796 ifname = InterfaceNameForID(m, InterfaceID);
5797 if (cr->CRActiveQuestion) CacheActive++;
5798 PrintOneCacheRecord(m, cr, slot, remain, ifname, &CacheUsed);
5799 PrintCachedRecords(m, cr, slot, remain, ifname, &CacheUsed);
5804 if (m->rrcache_totalused != CacheUsed)
5805 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
5806 if (m->rrcache_active != CacheActive)
5807 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
5808 LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed, CacheActive);
5810 LogMsgNoIdent("--------- Auth Records ---------");
5811 LogAuthRecords(m, now, m->ResourceRecords, mDNSNULL);
5813 LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
5814 LogLocalOnlyAuthRecords(m);
5816 LogMsgNoIdent("--------- /etc/hosts ---------");
5817 LogEtcHosts(m);
5819 LogMsgNoIdent("------ Duplicate Records -------");
5820 LogAuthRecords(m, now, m->DuplicateRecords, mDNSNULL);
5822 LogMsgNoIdent("----- Auth Records Proxied -----");
5823 LogAuthRecords(m, now, m->ResourceRecords, &ProxyA);
5825 LogMsgNoIdent("-- Duplicate Records Proxied ---");
5826 LogAuthRecords(m, now, m->DuplicateRecords, &ProxyD);
5828 LogMsgNoIdent("---------- Questions -----------");
5829 if (!m->Questions) LogMsgNoIdent("<None>");
5830 else
5832 char anonstr[256];
5833 CacheUsed = 0;
5834 CacheActive = 0;
5835 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
5836 for (q = m->Questions; q; q=q->next)
5838 mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
5839 mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
5840 char *ifname = InterfaceNameForID(m, q->InterfaceID);
5841 CacheUsed++;
5842 if (q->ThisQInterval) CacheActive++;
5843 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s%s",
5844 i, n,
5845 ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
5846 mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
5847 PrivateQuery(q) ? "P" : q->ValidationRequired ? "V" : q->ValidatingResponse ? "R" : " ",
5848 q->CurrentAnswers, q->validDNSServers.l[1], q->validDNSServers.l[0], q, q->DuplicateOf,
5849 q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c,
5850 AnonInfoToString(q->AnonInfo, anonstr, sizeof(anonstr)),
5851 q->DuplicateOf ? " (dup)" : "");
5853 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
5856 LogMsgNoIdent("----- Local-Only Questions -----");
5857 if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
5858 else for (q = m->LocalOnlyQuestions; q; q=q->next)
5859 LogMsgNoIdent(" %5d %-6s%##s%s",
5860 q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
5862 LogMsgNoIdent("---- Active UDS Client Requests ----");
5863 if (!all_requests) LogMsgNoIdent("<None>");
5864 else
5866 request_state *req, *r;
5867 for (req = all_requests; req; req=req->next)
5869 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
5871 for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
5872 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
5874 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
5875 LogClientInfo(m, req);
5876 foundparent:;
5880 LogMsgNoIdent("-------- NAT Traversals --------");
5881 LogMsgNoIdent("ExtAddress %.4a Retry %d Interval %d",
5882 &m->ExtAddress,
5883 m->retryGetAddr ? (m->retryGetAddr - now) / mDNSPlatformOneSecond : 0,
5884 m->retryIntervalGetAddr / mDNSPlatformOneSecond);
5885 if (m->NATTraversals)
5887 const NATTraversalInfo *nat;
5888 for (nat = m->NATTraversals; nat; nat=nat->next)
5890 LogMsgNoIdent("%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
5891 nat,
5892 nat->Protocol ? (nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP") : "ADD",
5893 mDNSVal16(nat->IntPort),
5894 (nat->lastSuccessfulProtocol == NATTProtocolNone ? "None " :
5895 nat->lastSuccessfulProtocol == NATTProtocolNATPMP ? "NAT-PMP " :
5896 nat->lastSuccessfulProtocol == NATTProtocolUPNPIGD ? "UPnP/IGD" :
5897 nat->lastSuccessfulProtocol == NATTProtocolPCP ? "PCP " :
5898 /* else */ "Unknown " ),
5899 nat->Result,
5900 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5901 nat->retryInterval / mDNSPlatformOneSecond,
5902 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5903 &nat->NewAddress, mDNSVal16(nat->RequestedPort),
5904 &nat->ExternalAddress, mDNSVal16(nat->ExternalPort));
5908 LogMsgNoIdent("--------- AuthInfoList ---------");
5909 if (!m->AuthInfoList) LogMsgNoIdent("<None>");
5910 else
5912 const DomainAuthInfo *a;
5913 for (a = m->AuthInfoList; a; a = a->next)
5915 LogMsgNoIdent("%##s %##s %##s %d %d %.16a%s",
5916 a->domain.c, a->keyname.c,
5917 a->hostname.c, (a->port.b[0] << 8 | a->port.b[1]),
5918 (a->deltime ? (a->deltime - now) : 0),
5919 &a->AutoTunnelInnerAddress, a->AutoTunnel ? " AutoTunnel" : "");
5923 #if APPLE_OSX_mDNSResponder
5924 LogMsgNoIdent("--------- TunnelClients --------");
5925 if (!m->TunnelClients) LogMsgNoIdent("<None>");
5926 else
5928 const ClientTunnel *c;
5929 for (c = m->TunnelClients; c; c = c->next)
5930 LogMsgNoIdent("%##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
5931 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);
5933 #endif // APPLE_OSX_mDNSResponder
5935 LogMsgNoIdent("---------- Misc State ----------");
5937 LogMsgNoIdent("PrimaryMAC: %.6a", &m->PrimaryMAC);
5939 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
5940 m->SleepState,
5941 m->SleepState == SleepState_Awake ? "Awake" :
5942 m->SleepState == SleepState_Transferring ? "Transferring" :
5943 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?",
5944 m->SleepSeqNum);
5946 if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
5947 #ifndef SPC_DISABLED
5948 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
5949 #endif
5950 if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
5951 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
5953 LogMsgNoIdent("------ Auto Browse Domains -----");
5954 if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
5955 else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5957 LogMsgNoIdent("--- Auto Registration Domains --");
5958 if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
5959 else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5961 LogMsgNoIdent("--- Search Domains --");
5962 if (!SearchList) LogMsgNoIdent("<None>");
5963 else
5965 for (s=SearchList; s; s=s->next)
5967 char *ifname = InterfaceNameForID(m, s->InterfaceID);
5968 LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
5971 LogInfo("--- Trust Anchors ---");
5972 if (!m->TrustAnchors)
5974 LogInfo("<None>");
5976 else
5978 TrustAnchor *ta;
5979 mDNSu8 fromTimeBuf[64];
5980 mDNSu8 untilTimeBuf[64];
5982 for (ta=m->TrustAnchors; ta; ta=ta->next)
5984 mDNSPlatformFormatTime((unsigned long)ta->validFrom, fromTimeBuf, sizeof(fromTimeBuf));
5985 mDNSPlatformFormatTime((unsigned long)ta->validUntil, untilTimeBuf, sizeof(untilTimeBuf));
5986 LogInfo("%##s %d %d %d %d %s %s", ta->zone.c, ta->rds.keyTag,
5987 ta->rds.alg, ta->rds.digestType, ta->digestLen, fromTimeBuf, untilTimeBuf);
5991 LogInfo("--- DNSSEC Statistics ---");
5993 LogInfo("Next Stats Time %u", m->NextStatLogTime - mDNSPlatformUTC());
5994 LogMsgNoIdent("Unicast Cache size %u", m->rrcache_totalused_unicast);
5995 LogInfo("DNSSEC Cache size %u", m->DNSSECStats.TotalMemUsed);
5996 if (m->rrcache_totalused_unicast)
5997 LogInfo("DNSSEC usage percentage %u", ((unsigned long)(m->DNSSECStats.TotalMemUsed * 100))/m->rrcache_totalused_unicast);
5998 LogInfo("DNSSEC Extra Packets (0 to 2) %u", m->DNSSECStats.ExtraPackets0);
5999 LogInfo("DNSSEC Extra Packets (3 to 6) %u", m->DNSSECStats.ExtraPackets3);
6000 LogInfo("DNSSEC Extra Packets (7 to 9) %u", m->DNSSECStats.ExtraPackets7);
6001 LogInfo("DNSSEC Extra Packets ( >= 10) %u", m->DNSSECStats.ExtraPackets10);
6003 LogInfo("DNSSEC Latency (0 to 4ms) %u", m->DNSSECStats.Latency0);
6004 LogInfo("DNSSEC Latency (4 to 9ms) %u", m->DNSSECStats.Latency5);
6005 LogInfo("DNSSEC Latency (10 to 19ms) %u", m->DNSSECStats.Latency10);
6006 LogInfo("DNSSEC Latency (20 to 49ms) %u", m->DNSSECStats.Latency20);
6007 LogInfo("DNSSEC Latency (50 to 99ms) %u", m->DNSSECStats.Latency50);
6008 LogInfo("DNSSEC Latency ( >=100ms) %u", m->DNSSECStats.Latency100);
6010 LogInfo("DNSSEC Secure Status %u", m->DNSSECStats.SecureStatus);
6011 LogInfo("DNSSEC Insecure Status %u", m->DNSSECStats.InsecureStatus);
6012 LogInfo("DNSSEC Indeterminate Status %u", m->DNSSECStats.IndeterminateStatus);
6013 LogInfo("DNSSEC Bogus Status %u", m->DNSSECStats.BogusStatus);
6014 LogInfo("DNSSEC NoResponse Status %u", m->DNSSECStats.NoResponseStatus);
6015 LogInfo("DNSSEC Probes sent %u", m->DNSSECStats.NumProbesSent);
6016 LogInfo("DNSSEC Msg Size (<=1024) %u", m->DNSSECStats.MsgSize0);
6017 LogInfo("DNSSEC Msg Size (<=2048) %u", m->DNSSECStats.MsgSize1);
6018 LogInfo("DNSSEC Msg Size (> 2048) %u", m->DNSSECStats.MsgSize2);
6020 LogMDNSStatistics(m);
6022 LogMsgNoIdent("---- Task Scheduling Timers ----");
6024 if (!m->NewQuestions)
6025 LogMsgNoIdent("NewQuestion <NONE>");
6026 else
6027 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
6028 m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
6029 m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
6031 if (!m->NewLocalOnlyQuestions)
6032 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
6033 else
6034 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
6035 m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
6037 if (!m->NewLocalRecords)
6038 LogMsgNoIdent("NewLocalRecords <NONE>");
6039 else
6040 LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
6042 LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
6043 LogMsgNoIdent("LocalRemoveEvents%s", m->LocalRemoveEvents ? "" : " <NONE>");
6044 LogMsgNoIdent("m->AutoTunnelRelayAddr %.16a", &m->AutoTunnelRelayAddr);
6045 LogMsgNoIdent("m->WABBrowseQueriesCount %d", m->WABBrowseQueriesCount);
6046 LogMsgNoIdent("m->WABLBrowseQueriesCount %d", m->WABLBrowseQueriesCount);
6047 LogMsgNoIdent("m->WABRegQueriesCount %d", m->WABRegQueriesCount);
6048 LogMsgNoIdent("m->AutoTargetServices %d", m->AutoTargetServices);
6050 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
6051 LogMsgNoIdent("m->timenow %08X %11d", now, now);
6052 LogMsgNoIdent("m->timenow_adjust %08X %11d", m->timenow_adjust, m->timenow_adjust);
6053 LogTimer("m->NextScheduledEvent ", m->NextScheduledEvent);
6055 #ifndef UNICAST_DISABLED
6056 LogTimer("m->NextuDNSEvent ", m->NextuDNSEvent);
6057 LogTimer("m->NextSRVUpdate ", m->NextSRVUpdate);
6058 LogTimer("m->NextScheduledNATOp ", m->NextScheduledNATOp);
6059 LogTimer("m->retryGetAddr ", m->retryGetAddr);
6060 #endif
6062 LogTimer("m->NextCacheCheck ", m->NextCacheCheck);
6063 LogTimer("m->NextScheduledSPS ", m->NextScheduledSPS);
6064 LogTimer("m->NextScheduledKA ", m->NextScheduledKA);
6065 LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
6066 LogTimer("m->DelaySleep ", m->DelaySleep);
6068 LogTimer("m->NextScheduledQuery ", m->NextScheduledQuery);
6069 LogTimer("m->NextScheduledProbe ", m->NextScheduledProbe);
6070 LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
6072 LogTimer("m->SuppressSending ", m->SuppressSending);
6073 LogTimer("m->SuppressProbes ", m->SuppressProbes);
6074 LogTimer("m->ProbeFailTime ", m->ProbeFailTime);
6075 LogTimer("m->DelaySleep ", m->DelaySleep);
6076 LogTimer("m->SleepLimit ", m->SleepLimit);
6077 LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
6080 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6081 mDNSexport void uds_validatelists(void)
6083 const request_state *req, *p;
6084 for (req = all_requests; req; req=req->next)
6086 if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
6087 LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
6089 if (req->primary == req)
6090 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
6092 if (req->primary && req->replies)
6093 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
6094 req, req->sd, req->primary && req->replies);
6096 p = req->primary;
6097 if ((long)p & 3)
6098 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
6099 else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
6100 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
6102 reply_state *rep;
6103 for (rep = req->replies; rep; rep=rep->next)
6104 if (rep->next == (reply_state *)~0)
6105 LogMemCorruption("UDS req->replies: %p is garbage", rep);
6107 if (req->terminate == connection_termination)
6109 registered_record_entry *r;
6110 for (r = req->u.reg_recs; r; r=r->next)
6111 if (r->next == (registered_record_entry *)~0)
6112 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
6114 else if (req->terminate == regservice_termination_callback)
6116 service_instance *s;
6117 for (s = req->u.servicereg.instances; s; s=s->next)
6118 if (s->next == (service_instance *)~0)
6119 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
6121 else if (req->terminate == browse_termination_callback)
6123 browser_t *b;
6124 for (b = req->u.browser.browsers; b; b=b->next)
6125 if (b->next == (browser_t *)~0)
6126 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
6130 DNameListElem *d;
6131 for (d = SCPrefBrowseDomains; d; d=d->next)
6132 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6133 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6135 ARListElem *b;
6136 for (b = LocalDomainEnumRecords; b; b=b->next)
6137 if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
6138 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
6140 for (d = AutoBrowseDomains; d; d=d->next)
6141 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6142 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6144 for (d = AutoRegistrationDomains; d; d=d->next)
6145 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6146 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
6148 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6150 mDNSlocal int send_msg(request_state *const req)
6152 reply_state *const rep = req->replies; // Send the first waiting reply
6153 ssize_t nwriten;
6155 ConvertHeaderBytes(rep->mhdr);
6156 nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
6157 ConvertHeaderBytes(rep->mhdr);
6159 if (nwriten < 0)
6161 if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
6162 else
6164 #if !defined(PLATFORM_NO_EPIPE)
6165 if (dnssd_errno == EPIPE)
6166 return(req->ts = t_terminated);
6167 else
6168 #endif
6170 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
6171 rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
6172 return(t_error);
6176 rep->nwriten += nwriten;
6177 return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
6180 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
6182 mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
6183 request_state **req = &all_requests;
6185 while (*req)
6187 request_state *const r = *req;
6189 if (r->terminate == resolve_termination_callback)
6190 if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
6192 r->u.resolve.ReportTime = 0;
6193 LogMsgNoIdent("Client application bug PID[%d](%s) : DNSServiceResolve(%##s) active for over two minutes. "
6194 "This places considerable burden on the network.", r->process_id, r->pid_name, r->u.resolve.qsrv.qname.c);
6197 // Note: Only primary req's have reply lists, not subordinate req's.
6198 while (r->replies) // Send queued replies
6200 transfer_state result;
6201 if (r->replies->next)
6202 r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
6203 result = send_msg(r); // Returns t_morecoming if buffer full because client is not reading
6204 if (result == t_complete)
6206 reply_state *fptr = r->replies;
6207 r->replies = r->replies->next;
6208 freeL("reply_state/udsserver_idle", fptr);
6209 r->time_blocked = 0; // reset failure counter after successful send
6210 r->unresponsiveness_reports = 0;
6211 continue;
6213 else if (result == t_terminated || result == t_error)
6215 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r->sd, r->process_id, r->pid_name);
6216 LogClientInfo(&mDNSStorage, r);
6217 abort_request(r);
6219 break;
6222 if (r->replies) // If we failed to send everything, check our time_blocked timer
6224 if (nextevent - now > mDNSPlatformOneSecond)
6225 nextevent = now + mDNSPlatformOneSecond;
6227 if (mDNSStorage.SleepState != SleepState_Awake)
6228 r->time_blocked = 0;
6229 else if (!r->time_blocked)
6230 r->time_blocked = NonZeroTime(now);
6231 else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
6233 int num = 0;
6234 struct reply_state *x = r->replies;
6235 while (x)
6237 num++;
6238 x=x->next;
6240 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
6241 r->sd, r->process_id, r->pid_name, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
6242 if (++r->unresponsiveness_reports >= 60)
6244 LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r->sd, r->process_id, r->pid_name);
6245 LogClientInfo(&mDNSStorage, r);
6246 abort_request(r);
6251 if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
6253 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
6254 *req = r->next;
6255 freeL("request_state/udsserver_idle", r);
6257 else
6258 req = &r->next;
6260 return nextevent;
6263 struct CompileTimeAssertionChecks_uds_daemon
6265 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
6266 // other overly-large structures instead of having a pointer to them, can inadvertently
6267 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
6268 char sizecheck_request_state [(sizeof(request_state) <= 2000) ? 1 : -1];
6269 char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <= 60) ? 1 : -1];
6270 char sizecheck_service_instance [(sizeof(service_instance) <= 6552) ? 1 : -1];
6271 char sizecheck_browser_t [(sizeof(browser_t) <= 1128) ? 1 : -1];
6272 char sizecheck_reply_hdr [(sizeof(reply_hdr) <= 12) ? 1 : -1];
6273 char sizecheck_reply_state [(sizeof(reply_state) <= 64) ? 1 : -1];