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