1 /* -*- Mode: C; tab-width: 4 -*- 2 * 3 * Copyright (c) 2003-2004 Apple Computer, Inc. All rights reserved. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 17 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 41 #if __APPLE__ 42 #undef daemon 43 extern int daemon(int, int); 44 #endif 45 46 #include "mDNSEmbeddedAPI.h" 47 #include "mDNSPosix.h" 48 #include "mDNSUNP.h" // For daemon() 49 #include "uds_daemon.h" 50 #include "PlatformCommon.h" 51 #include "DNSCommon.h" 52 53 #define CONFIG_FILE "/etc/mdnsd.conf" 54 static domainname DynDNSZone; // Default wide-area zone for service registration 55 static domainname DynDNSHostname; 56 57 #define RR_CACHE_SIZE 500 58 static CacheEntity gRRCache[RR_CACHE_SIZE]; 59 static mDNS_PlatformSupport PlatformStorage; 60 61 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result) 62 { 63 (void)m; // Unused 64 if (result == mStatus_NoError) 65 { 66 // On successful registration of dot-local mDNS host name, daemon may want to check if 67 // any name conflict and automatic renaming took place, and if so, record the newly negotiated 68 // name in persistent storage for next time. It should also inform the user of the name change. 69 // On Mac OS X we store the current dot-local mDNS host name in the SCPreferences store, 70 // and notify the user with a CFUserNotification. 71 } 72 else if (result == mStatus_ConfigChanged) 73 { 74 udsserver_handle_configchange(m); 75 } 76 else if (result == mStatus_GrowCache) 77 { 78 // Allocate another chunk of cache storage 79 CacheEntity *storage = malloc(sizeof(CacheEntity) * RR_CACHE_SIZE); 80 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE); 81 } 82 } 83 84 // %%% Reconfigure() probably belongs in the platform support layer (mDNSPosix.c), not the daemon cde 85 // -- all client layers running on top of mDNSPosix.c need to handle network configuration changes, 86 // not only the Unix Domain Socket Daemon 87 88 static void Reconfigure(mDNS *m) 89 { 90 mDNSAddr DynDNSIP; 91 const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 1, 1, 1, 1 } } } };; 92 mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL); 93 mDNS_Lock(m); 94 if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0) 95 LogInfo("Unable to parse DNS server list. Unicast DNS-SD unavailable"); 96 mDNS_Unlock(m); 97 ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL); 98 mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy); 99 if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL); 100 if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL); 101 mDNS_ConfigChanged(m); 102 } 103 104 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy. 105 mDNSlocal void ParseCmdLinArgs(int argc, char **argv) 106 { 107 if (argc > 1) 108 { 109 if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue; 110 else printf("Usage: %s [-debug]\n", argv[0]); 111 } 112 113 if (!mDNS_DebugMode) 114 { 115 int result = daemon(0, 0); 116 if (result != 0) { LogMsg("Could not run as daemon - exiting"); exit(result); } 117 #if __APPLE__ 118 LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting"); 119 exit(-1); 120 #endif 121 } 122 } 123 124 mDNSlocal void DumpStateLog() 125 // Dump a little log of what we've been up to. 126 { 127 LogMsg("---- BEGIN STATE LOG ----"); 128 udsserver_info(); 129 LogMsg("---- END STATE LOG ----"); 130 } 131 132 mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit. 133 { 134 sigset_t signals; 135 mDNSBool gotData = mDNSfalse; 136 137 mDNSPosixListenForSignalInEventLoop(SIGINT); 138 mDNSPosixListenForSignalInEventLoop(SIGTERM); 139 mDNSPosixListenForSignalInEventLoop(SIGUSR1); 140 mDNSPosixListenForSignalInEventLoop(SIGPIPE); 141 mDNSPosixListenForSignalInEventLoop(SIGHUP) ; 142 143 for (; ;) 144 { 145 // Work out how long we expect to sleep before the next scheduled task 146 struct timeval timeout; 147 mDNSs32 ticks; 148 149 // Only idle if we didn't find any data the last time around 150 if (!gotData) 151 { 152 mDNSs32 nextTimerEvent = mDNS_Execute(m); 153 nextTimerEvent = udsserver_idle(nextTimerEvent); 154 ticks = nextTimerEvent - mDNS_TimeNow(m); 155 if (ticks < 1) ticks = 1; 156 } 157 else // otherwise call EventLoop again with 0 timemout 158 ticks = 0; 159 160 timeout.tv_sec = ticks / mDNSPlatformOneSecond; 161 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond; 162 163 (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData); 164 165 if (sigismember(&signals, SIGHUP )) Reconfigure(m); 166 if (sigismember(&signals, SIGUSR1)) DumpStateLog(); 167 // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up. 168 if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring"); 169 if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break; 170 } 171 return EINTR; 172 } 173 174 int main(int argc, char **argv) 175 { 176 mStatus err; 177 178 ParseCmdLinArgs(argc, argv); 179 180 LogInfo("%s starting", mDNSResponderVersionString); 181 182 err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses, 183 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext); 184 185 if (mStatus_NoError == err) 186 err = udsserver_init(mDNSNULL, 0); 187 188 Reconfigure(&mDNSStorage); 189 190 // Now that we're finished with anything privileged, switch over to running as "nobody" 191 if (mStatus_NoError == err) 192 { 193 const struct passwd *pw = getpwnam("nobody"); 194 if (pw != NULL) 195 setuid(pw->pw_uid); 196 else 197 LogMsg("WARNING: mdnsd continuing as root because user \"nobody\" does not exist"); 198 } 199 200 if (mStatus_NoError == err) 201 err = MainLoop(&mDNSStorage); 202 203 LogInfo("%s stopping", mDNSResponderVersionString); 204 205 mDNS_Close(&mDNSStorage); 206 207 if (udsserver_exit() < 0) 208 LogMsg("ExitCallback: udsserver_exit failed"); 209 210 #if MDNS_DEBUGMSGS > 0 211 printf("mDNSResponder exiting normally with %ld\n", err); 212 #endif 213 214 return err; 215 } 216 217 // uds_daemon support //////////////////////////////////////////////////////////// 218 219 mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data) 220 /* Support routine for uds_daemon.c */ 221 { 222 // Depends on the fact that udsEventCallback == mDNSPosixEventCallback 223 (void) platform_data; 224 return mDNSPosixAddFDToEventLoop(fd, callback, context); 225 } 226 227 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data) 228 { 229 (void) platform_data; 230 return recv(fd, buf, len, flags); 231 } 232 233 mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor 234 { 235 mStatus err = mDNSPosixRemoveFDFromEventLoop(fd); 236 (void) platform_data; 237 close(fd); 238 return err; 239 } 240 241 mDNSexport void RecordUpdatedNiceLabel(mDNSs32 delay) 242 { 243 (void)delay; 244 // No-op, for now 245 } 246 247 #if _BUILDING_XCODE_PROJECT_ 248 // If the process crashes, then this string will be magically included in the automatically-generated crash log 249 const char *__crashreporter_info__ = mDNSResponderVersionString_SCCS + 5; 250 asm (".desc ___crashreporter_info__, 0x10"); 251 #endif 252 253 // For convenience when using the "strings" command, this is the last thing in the file 254 #if mDNSResponderVersion > 1 255 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder-" STRINGIFY(mDNSResponderVersion) 256 #ifndef MDNS_VERSIONSTR_NODTS 257 " (" __DATE__ " " __TIME__ ")" 258 #endif 259 ; 260 #else 261 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)" 262 #ifndef MDNS_VERSIONSTR_NODTS 263 " (" __DATE__ " " __TIME__ ")" 264 #endif 265 ; 266 #endif 267