1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*- 2 * 3 * Copyright (c) 2003-2024 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 * https://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 File: daemon.c 18 19 Contains: main & associated Application layer for mDNSResponder on Linux. 20 21 */ 22 23 #if __APPLE__ 24 // In Mac OS X 10.5 and later trying to use the daemon function gives a “‘daemon’ is deprecated” 25 // error, which prevents compilation because we build with "-Werror". 26 // Since this is supposed to be portable cross-platform code, we don't care that daemon is 27 // deprecated on Mac OS X 10.5, so we use this preprocessor trick to eliminate the error message. 28 #define daemon yes_we_know_that_daemon_is_deprecated_in_os_x_10_5_thankyou 29 #endif 30 31 #include <stdio.h> 32 #include <string.h> 33 #include <unistd.h> 34 #include <stdlib.h> 35 #include <signal.h> 36 #include <errno.h> 37 #include <fcntl.h> 38 #include <pwd.h> 39 #include <sys/types.h> 40 #include <sys/socket.h> 41 42 #if __APPLE__ 43 #undef daemon 44 extern int daemon(int, int); 45 #endif 46 47 #include "mDNSEmbeddedAPI.h" 48 #include "mDNSPosix.h" 49 #include "mDNSUNP.h" // For daemon() 50 #include "uds_daemon.h" 51 #include "PlatformCommon.h" 52 #include "DNSCommon.h" 53 54 #ifndef MDNSD_USER 55 #define MDNSD_USER "nobody" 56 #endif 57 58 #define CONFIG_FILE "/etc/mdnsd.conf" 59 static domainname DynDNSZone; // Default wide-area zone for service registration 60 static domainname DynDNSHostname; 61 62 #define RR_CACHE_SIZE 500 63 static CacheEntity gRRCache[RR_CACHE_SIZE]; 64 static mDNS_PlatformSupport PlatformStorage; 65 66 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result) 67 { 68 (void)m; // Unused 69 if (result == mStatus_NoError) 70 { 71 // On successful registration of dot-local mDNS host name, daemon may want to check if 72 // any name conflict and automatic renaming took place, and if so, record the newly negotiated 73 // name in persistent storage for next time. It should also inform the user of the name change. 74 // On Mac OS X we store the current dot-local mDNS host name in the SCPreferences store, 75 // and notify the user with a CFUserNotification. 76 } 77 else if (result == mStatus_ConfigChanged) 78 { 79 udsserver_handle_configchange(m); 80 } 81 else if (result == mStatus_GrowCache) 82 { 83 // Allocate another chunk of cache storage 84 CacheEntity *storage = malloc(sizeof(CacheEntity) * RR_CACHE_SIZE); 85 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE); 86 } 87 } 88 89 // %%% Reconfigure() probably belongs in the platform support layer (mDNSPosix.c), not the daemon cde 90 // -- all client layers running on top of mDNSPosix.c need to handle network configuration changes, 91 // not only the Unix Domain Socket Daemon 92 93 static void Reconfigure(mDNS *m) 94 { 95 mDNSAddr DynDNSIP; 96 const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 198, 51, 100, 42 } } } };; 97 mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL); 98 mDNS_Lock(m); 99 if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0) 100 LogInfo("Unable to parse DNS server list. Unicast DNS-SD unavailable"); 101 mDNS_Unlock(m); 102 ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL); 103 mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy); 104 if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL); 105 if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL); 106 mDNS_ConfigChanged(m); 107 } 108 109 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy. 110 mDNSlocal void ParseCmdLineArgs(int argc, char **argv) 111 { 112 if (argc > 1) 113 { 114 if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue; 115 else printf("Usage: %s [-debug]\n", argv[0]); 116 } 117 if (!mDNS_DebugMode) 118 { 119 int result = daemon(0, 0); 120 if (result != 0) { LogMsg("Could not run as daemon - exiting"); exit(result); } 121 #if __APPLE__ 122 LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting"); 123 exit(-1); 124 #endif 125 } 126 } 127 128 mDNSlocal void DumpStateLog(mDNS *const m) 129 // Dump a little log of what we've been up to. 130 { 131 char timestamp[MIN_TIMESTAMP_STRING_LENGTH]; 132 133 mDNSu32 major_version = _DNS_SD_H / 10000; 134 mDNSu32 minor_version1 = (_DNS_SD_H - major_version * 10000) / 100; 135 mDNSu32 minor_version2 = _DNS_SD_H % 100; 136 137 getLocalTimestampNow(timestamp, sizeof(timestamp)); 138 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- BEGIN STATE LOG ---- (%s mDNSResponder Build %d.%02d.%02d)", timestamp, major_version, minor_version1, minor_version2); 139 140 udsserver_info_dump_to_fd(STDERR_FILENO); 141 142 getLocalTimestampNow(timestamp, sizeof(timestamp)); 143 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- END STATE LOG ---- (%s mDNSResponder Build %d.%02d.%02d)", timestamp, major_version, minor_version1, minor_version2); 144 } 145 146 mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit. 147 { 148 sigset_t signals; 149 mDNSBool gotData = mDNSfalse; 150 151 mDNSPosixListenForSignalInEventLoop(SIGINT); 152 mDNSPosixListenForSignalInEventLoop(SIGTERM); 153 mDNSPosixListenForSignalInEventLoop(SIGUSR1); 154 mDNSPosixListenForSignalInEventLoop(SIGUSR2); 155 mDNSPosixListenForSignalInEventLoop(SIGPIPE); 156 mDNSPosixListenForSignalInEventLoop(SIGHUP) ; 157 158 for (; ;) 159 { 160 // Work out how long we expect to sleep before the next scheduled task 161 struct timeval timeout; 162 mDNSs32 ticks; 163 164 // Only idle if we didn't find any data the last time around 165 if (!gotData) 166 { 167 mDNSs32 nextTimerEvent = mDNS_Execute(m); 168 nextTimerEvent = udsserver_idle(nextTimerEvent); 169 ticks = nextTimerEvent - mDNS_TimeNow(m); 170 if (ticks < 1) ticks = 1; 171 } 172 else // otherwise call EventLoop again with 0 timemout 173 ticks = 0; 174 175 timeout.tv_sec = ticks / mDNSPlatformOneSecond; 176 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond; 177 178 (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData); 179 180 if (sigismember(&signals, SIGHUP )) Reconfigure(m); 181 if (sigismember(&signals, SIGUSR1)) DumpStateLog(m); 182 if (sigismember(&signals, SIGUSR2)) 183 { 184 mDNS_DebugLoggingEnabled = !mDNS_DebugLoggingEnabled; 185 LogMsg("Received SIGUSR2 - %s debug level logging.", mDNS_DebugLoggingEnabled ? "Enable" : "Disable"); 186 } 187 // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up. 188 if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring"); 189 if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break; 190 } 191 return EINTR; 192 } 193 194 int main(int argc, char **argv) 195 { 196 mStatus err; 197 198 ParseCmdLineArgs(argc, argv); 199 200 // Enable mDNSResponder logging by default. 201 mDNS_LoggingEnabled = mDNStrue; 202 203 LogInfo("%s starting", mDNSResponderVersionString); 204 205 err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses, 206 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext); 207 208 if (mStatus_NoError == err) 209 err = udsserver_init(mDNSNULL, 0); 210 211 Reconfigure(&mDNSStorage); 212 213 // Now that we're finished with anything privileged, switch over to running as "nobody" 214 if (mStatus_NoError == err) 215 { 216 const struct passwd *pw = getpwnam(MDNSD_USER); 217 if (pw != NULL) 218 { 219 if (setgid(pw->pw_gid) < 0) 220 { 221 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, 222 "WARNING: mdnsd continuing as group root because setgid to \"nobody\" failed with " PUB_S, strerror(errno)); 223 } 224 if (setuid(pw->pw_uid) < 0) 225 { 226 LogMsg("WARNING: mdnsd continuing as root because setuid to \"nobody\" failed with %s", strerror(errno)); 227 } 228 } 229 else 230 { 231 LogMsg("WARNING: mdnsd continuing as root because user \"nobody\" does not exist"); 232 } 233 } 234 235 if (mStatus_NoError == err) 236 err = MainLoop(&mDNSStorage); 237 238 LogInfo("%s stopping", mDNSResponderVersionString); 239 240 mDNS_Close(&mDNSStorage); 241 242 if (udsserver_exit() < 0) 243 LogMsg("ExitCallback: udsserver_exit failed"); 244 245 #if MDNS_DEBUGMSGS > 0 246 printf("mDNSResponder exiting normally with %d\n", err); 247 #endif 248 249 return err; 250 } 251 252 // uds_daemon support //////////////////////////////////////////////////////////// 253 254 mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data) 255 /* Support routine for uds_daemon.c */ 256 { 257 // Depends on the fact that udsEventCallback == mDNSPosixEventCallback 258 (void) platform_data; 259 return mDNSPosixAddFDToEventLoop(fd, callback, context); 260 } 261 262 ssize_t udsSupportReadFD(dnssd_sock_t fd, char *buf, mDNSu32 len, int flags, void *platform_data) 263 { 264 (void) platform_data; 265 return recv(fd, buf, len, flags); 266 } 267 268 mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor 269 { 270 mStatus err = mDNSPosixRemoveFDFromEventLoop(fd); 271 (void) platform_data; 272 close(fd); 273 return err; 274 } 275 276 mDNSexport void RecordUpdatedNiceLabel(mDNSs32 delay) 277 { 278 (void)delay; 279 // No-op, for now 280 } 281 282 #if _BUILDING_XCODE_PROJECT_ 283 // If the process crashes, then this string will be magically included in the automatically-generated crash log 284 const char *__crashreporter_info__ = mDNSResponderVersionString_SCCS + 5; 285 asm (".desc ___crashreporter_info__, 0x10"); 286 #endif 287 288 // For convenience when using the "strings" command, this is the last thing in the file 289 #if mDNSResponderVersion > 1 290 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder-" STRINGIFY(mDNSResponderVersion) 291 #ifndef MDNS_VERSIONSTR_NODTS 292 " (" __DATE__ " " __TIME__ ")" 293 #endif 294 ; 295 #else 296 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)" 297 #ifndef MDNS_VERSIONSTR_NODTS 298 " (" __DATE__ " " __TIME__ ")" 299 #endif 300 ; 301 #endif 302