PosixDaemon.c revision 1.1.1.3 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 "DNSCommon.h"
51 #include "PlatformCommon.h"
52
53 #ifndef MDNSD_USER
54 #define MDNSD_USER "nobody"
55 #endif
56
57 #define CONFIG_FILE "/etc/mdnsd.conf"
58 static domainname DynDNSZone; // Default wide-area zone for service registration
59 static domainname DynDNSHostname;
60
61 #define RR_CACHE_SIZE 500
62 static CacheEntity gRRCache[RR_CACHE_SIZE];
63 static mDNS_PlatformSupport PlatformStorage;
64
65 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
66 {
67 (void)m; // Unused
68 if (result == mStatus_NoError)
69 {
70 // On successful registration of dot-local mDNS host name, daemon may want to check if
71 // any name conflict and automatic renaming took place, and if so, record the newly negotiated
72 // name in persistent storage for next time. It should also inform the user of the name change.
73 // On Mac OS X we store the current dot-local mDNS host name in the SCPreferences store,
74 // and notify the user with a CFUserNotification.
75 }
76 else if (result == mStatus_ConfigChanged)
77 {
78 udsserver_handle_configchange(m);
79 }
80 else if (result == mStatus_GrowCache)
81 {
82 // Allocate another chunk of cache storage
83 CacheEntity *storage = malloc(sizeof(CacheEntity) * RR_CACHE_SIZE);
84 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
85 }
86 }
87
88 // %%% Reconfigure() probably belongs in the platform support layer (mDNSPosix.c), not the daemon cde
89 // -- all client layers running on top of mDNSPosix.c need to handle network configuration changes,
90 // not only the Unix Domain Socket Daemon
91
92 static void Reconfigure(mDNS *m)
93 {
94 mDNSAddr DynDNSIP;
95 const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 1, 1, 1, 1 } } } };;
96 mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL);
97 mDNS_Lock(m);
98 if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0)
99 LogMsg("Unable to parse DNS server list. Unicast DNS-SD unavailable");
100 mDNS_Unlock(m);
101 ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL);
102 mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy);
103 if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL);
104 if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL);
105 mDNS_ConfigChanged(m);
106 }
107
108 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy.
109 mDNSlocal void ParseCmdLinArgs(int argc, char **argv)
110 {
111 if (argc > 1)
112 {
113 if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue;
114 else printf("Usage: %s [-debug]\n", argv[0]);
115 }
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 DNSServer *s;
132 PosixNetworkInterface *i;
133
134 LogMsg("---- BEGIN STATE LOG ----");
135 udsserver_info(m);
136
137 LogMsgNoIdent("----- Network Interfaces -------");
138 for (i = (PosixNetworkInterface*)(m->HostInterfaces);
139 i; i = (PosixNetworkInterface *)(i->coreIntf.next)) {
140 LogMsg("%p %p %d %s%s%s%s%s %-8s %#a", i,
141 (void *)(i->coreIntf.InterfaceID), i->index,
142 i->coreIntf.InterfaceActive ? "-" : "D",
143 i->coreIntf.IPv4Available ? "4" : "-",
144 i->coreIntf.IPv6Available ? "6" : "-",
145 i->coreIntf.Advertise ? "A" : "-",
146 i->coreIntf.McastTxRx ? "M" : "-",
147 i->intfName, &(i->coreIntf.ip));
148 }
149
150 LogMsgNoIdent("--------- DNS Servers ----------");
151 if (!mDNSStorage.DNSServers) LogMsgNoIdent("<None>");
152 else
153 {
154 for (s = m->DNSServers; s; s = s->next)
155 {
156 LogMsgNoIdent("DNS Server %##s %#a:%d %s",
157 s->domain.c, &s->addr, mDNSVal16(s->port),
158 s->teststate == DNSServer_Untested ? "(Untested)" :
159 s->teststate == DNSServer_Passed ? "" :
160 s->teststate == DNSServer_Failed ? "(Failed)" :
161 s->teststate == DNSServer_Disabled ? "(Disabled)" : "(Unknown state)");
162 }
163 }
164
165 LogMsg("---- END STATE LOG ----");
166 }
167
168 mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit.
169 {
170 sigset_t signals;
171 mDNSBool gotData = mDNSfalse;
172
173 mDNSPosixListenForSignalInEventLoop(SIGINT);
174 mDNSPosixListenForSignalInEventLoop(SIGTERM);
175 mDNSPosixListenForSignalInEventLoop(SIGUSR1);
176 #ifdef HAVE_SIGINFO
177 mDNSPosixListenForSignalInEventLoop(SIGUSR2);
178 mDNSPosixListenForSignalInEventLoop(SIGINFO);
179 #endif
180 mDNSPosixListenForSignalInEventLoop(SIGPIPE);
181 mDNSPosixListenForSignalInEventLoop(SIGHUP) ;
182
183 for (; ;)
184 {
185 // Work out how long we expect to sleep before the next scheduled task
186 struct timeval timeout;
187 mDNSs32 ticks;
188
189 // Only idle if we didn't find any data the last time around
190 if (!gotData)
191 {
192 mDNSs32 nextTimerEvent = mDNS_Execute(m);
193 nextTimerEvent = udsserver_idle(nextTimerEvent);
194 ticks = nextTimerEvent - mDNS_TimeNow(m);
195 if (ticks < 1) ticks = 1;
196 }
197 else // otherwise call EventLoop again with 0 timemout
198 ticks = 0;
199
200 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
201 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond;
202
203 (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData);
204
205 if (sigismember(&signals, SIGHUP )) Reconfigure(m);
206 #ifdef HAVE_SIGINFO
207 /* use OSX-compatible signals since we can, and gain enhanced debugging */
208 if (sigismember(&signals, SIGINFO)) DumpStateLog(m);
209 if (sigismember(&signals, SIGUSR1))
210 {
211 mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
212 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
213 }
214 if (sigismember(&signals, SIGUSR2))
215 {
216 mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
217 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
218 }
219 #else
220 if (sigismember(&signals, SIGUSR1)) DumpStateLog(m);
221 #endif
222 // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up.
223 if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring");
224 if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break;
225 }
226 return EINTR;
227 }
228
229 int main(int argc, char **argv)
230 {
231 mStatus err;
232
233 ParseCmdLinArgs(argc, argv);
234
235 LogMsg("%s starting", mDNSResponderVersionString);
236
237 err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses,
238 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
239
240 if (mStatus_NoError == err)
241 err = udsserver_init(mDNSNULL, 0);
242
243 Reconfigure(&mDNSStorage);
244
245 // Now that we're finished with anything privileged, switch over to running as "nobody"
246 if (mStatus_NoError == err)
247 {
248 const struct passwd *pw = getpwnam(MDNSD_USER);
249 if (pw != NULL)
250 {
251 setgid(pw->pw_gid);
252 setuid(pw->pw_uid);
253 }
254 else
255 #ifdef MDNSD_NOROOT
256 {
257 LogMsg("WARNING: mdnsd exiting because user \""MDNSD_USER"\" does not exist");
258 err = mStatus_Invalid;
259 }
260 #else
261 LogMsg("WARNING: mdnsd continuing as root because user \""MDNSD_USER"\" does not exist");
262 #endif
263 }
264
265 if (mStatus_NoError == err)
266 err = MainLoop(&mDNSStorage);
267
268 LogMsg("%s stopping", mDNSResponderVersionString);
269
270 mDNS_Close(&mDNSStorage);
271
272 if (udsserver_exit() < 0)
273 LogMsg("ExitCallback: udsserver_exit failed");
274
275 #if MDNS_DEBUGMSGS > 0
276 printf("mDNSResponder exiting normally with %ld\n", err);
277 #endif
278
279 return err;
280 }
281
282 // uds_daemon support ////////////////////////////////////////////////////////////
283
284 mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
285 /* Support routine for uds_daemon.c */
286 {
287 // Depends on the fact that udsEventCallback == mDNSPosixEventCallback
288 (void) platform_data;
289 return mDNSPosixAddFDToEventLoop(fd, callback, context);
290 }
291
292 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
293 {
294 (void) platform_data;
295 return recv(fd, buf, len, flags);
296 }
297
298 mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor
299 {
300 mStatus err = mDNSPosixRemoveFDFromEventLoop(fd);
301 (void) platform_data;
302 close(fd);
303 return err;
304 }
305
306 mDNSexport void RecordUpdatedNiceLabel(mDNS *const m, mDNSs32 delay)
307 {
308 (void)m;
309 (void)delay;
310 // No-op, for now
311 }
312
313 #if _BUILDING_XCODE_PROJECT_
314 // If the process crashes, then this string will be magically included in the automatically-generated crash log
315 const char *__crashreporter_info__ = mDNSResponderVersionString_SCCS + 5;
316 asm(".desc ___crashreporter_info__, 0x10");
317 #endif
318
319 // For convenience when using the "strings" command, this is the last thing in the file
320 #if mDNSResponderVersion > 1
321 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder-" STRINGIFY(mDNSResponderVersion);
322 #elif MDNS_VERSIONSTR_NODTS
323 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)";
324 #else
325 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)";
326 #endif
327