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