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