]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSPosix/PosixDaemon.c
mDNSResponder-164.tar.gz
[apple/mdnsresponder.git] / mDNSPosix / PosixDaemon.c
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 Change History (most recent first):
22
23 $Log: PosixDaemon.c,v $
24 Revision 1.43 2007/10/22 20:05:34 cheshire
25 Use mDNSPlatformSourceAddrForDest instead of FindSourceAddrForIP
26
27 Revision 1.42 2007/09/18 19:09:02 cheshire
28 <rdar://problem/5489549> mDNSResponderHelper (and other binaries) missing SCCS version strings
29
30 Revision 1.41 2007/09/04 17:02:25 cheshire
31 <rdar://problem/5458929> False positives in changed files list in nightly builds
32 Added MDNS_VERSIONSTR_NODTS option at the reqest of Rishi Srivatsavai (Sun)
33
34 Revision 1.40 2007/07/31 23:08:34 mcguire
35 <rdar://problem/5329542> BTMM: Make AutoTunnel mode work with multihoming
36
37 Revision 1.39 2007/03/21 00:30:44 cheshire
38 Remove obsolete mDNS_DeleteDNSServers() call
39
40 Revision 1.38 2007/02/14 01:58:19 cheshire
41 <rdar://problem/4995831> Don't delete Unix Domain Socket on exit if we didn't create it on startup
42
43 Revision 1.37 2007/02/07 19:32:00 cheshire
44 <rdar://problem/4980353> All mDNSResponder components should contain version strings in SCCS-compatible format
45
46 Revision 1.36 2007/02/06 19:06:48 cheshire
47 <rdar://problem/3956518> Need to go native with launchd
48
49 Revision 1.35 2007/01/05 08:30:52 cheshire
50 Trim excessive "$Log" checkin history from before 2006
51 (checkin history still available via "cvs log ..." of course)
52
53 Revision 1.34 2007/01/05 05:46:08 cheshire
54 Add mDNS *const m parameter to udsserver_handle_configchange()
55
56 Revision 1.33 2006/12/21 00:10:53 cheshire
57 Make mDNS_PlatformSupport PlatformStorage a static global instead of a stack variable
58
59 Revision 1.32 2006/11/03 22:28:50 cheshire
60 PosixDaemon needs to handle mStatus_ConfigChanged and mStatus_GrowCache messages
61
62 Revision 1.31 2006/08/14 23:24:46 cheshire
63 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
64
65 Revision 1.30 2006/07/07 01:09:12 cheshire
66 <rdar://problem/4472013> Add Private DNS server functionality to dnsextd
67 Only use mallocL/freeL debugging routines when building mDNSResponder, not dnsextd
68
69 */
70
71 #include <stdio.h>
72 #include <string.h>
73 #include <unistd.h>
74 #include <stdlib.h>
75 #include <signal.h>
76 #include <errno.h>
77 #include <fcntl.h>
78 #include <pwd.h>
79 #include <sys/types.h>
80
81 #include "mDNSEmbeddedAPI.h"
82 #include "mDNSDebug.h"
83 #include "mDNSPosix.h"
84 #include "uds_daemon.h"
85 #include "PlatformCommon.h"
86
87 #define CONFIG_FILE "/etc/mdnsd.conf"
88 static domainname DynDNSZone; // Default wide-area zone for service registration
89 static domainname DynDNSHostname;
90
91 #define RR_CACHE_SIZE 500
92 static CacheEntity gRRCache[RR_CACHE_SIZE];
93 static mDNS_PlatformSupport PlatformStorage;
94
95 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
96 {
97 (void)m; // Unused
98 if (result == mStatus_NoError)
99 {
100 // On successful registration of dot-local mDNS host name, daemon may want to check if
101 // any name conflict and automatic renaming took place, and if so, record the newly negotiated
102 // name in persistent storage for next time. It should also inform the user of the name change.
103 // On Mac OS X we store the current dot-local mDNS host name in the SCPreferences store,
104 // and notify the user with a CFUserNotification.
105 }
106 else if (result == mStatus_ConfigChanged)
107 {
108 udsserver_handle_configchange(m);
109 }
110 else if (result == mStatus_GrowCache)
111 {
112 // Allocate another chunk of cache storage
113 CacheEntity *storage = malloc(sizeof(CacheEntity) * RR_CACHE_SIZE);
114 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
115 }
116 }
117
118 // %%% Reconfigure() probably belongs in the platform support layer (mDNSPosix.c), not the daemon cde
119 // -- all client layers running on top of mDNSPosix.c need to handle network configuration changes,
120 // not only the Unix Domain Socket Daemon
121
122 static void Reconfigure(mDNS *m)
123 {
124 mDNSAddr DynDNSIP;
125 const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 1, 1, 1, 1 } } } };;
126 mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL);
127 if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0)
128 LogMsg("Unable to parse DNS server list. Unicast DNS-SD unavailable");
129 ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL);
130 mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy);
131 if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL);
132 if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL);
133 m->MainCallback(m, mStatus_ConfigChanged);
134 }
135
136 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy.
137 mDNSlocal void ParseCmdLinArgs(int argc, char **argv)
138 {
139 if (argc > 1)
140 {
141 if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue;
142 else printf("Usage: %s [-debug]\n", argv[0]);
143 }
144
145 if (!mDNS_DebugMode)
146 {
147 int result = daemon(0, 0);
148 if (result != 0) { LogMsg("Could not run as daemon - exiting"); exit(result); }
149 #if __APPLE__
150 LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting");
151 exit(-1);
152 #endif
153 }
154 }
155
156 mDNSlocal void DumpStateLog(mDNS *const m)
157 // Dump a little log of what we've been up to.
158 {
159 LogMsgIdent(mDNSResponderVersionString, "---- BEGIN STATE LOG ----");
160 udsserver_info(m);
161 LogMsgIdent(mDNSResponderVersionString, "---- END STATE LOG ----");
162 }
163
164 mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit.
165 {
166 sigset_t signals;
167 mDNSBool gotData = mDNSfalse;
168
169 mDNSPosixListenForSignalInEventLoop(SIGINT);
170 mDNSPosixListenForSignalInEventLoop(SIGTERM);
171 mDNSPosixListenForSignalInEventLoop(SIGUSR1);
172 mDNSPosixListenForSignalInEventLoop(SIGPIPE);
173 mDNSPosixListenForSignalInEventLoop(SIGHUP) ;
174
175 for (; ;)
176 {
177 // Work out how long we expect to sleep before the next scheduled task
178 struct timeval timeout;
179 mDNSs32 ticks;
180
181 // Only idle if we didn't find any data the last time around
182 if (!gotData)
183 {
184 mDNSs32 nextTimerEvent = mDNS_Execute(m);
185 nextTimerEvent = udsserver_idle(nextTimerEvent);
186 ticks = nextTimerEvent - mDNS_TimeNow(m);
187 if (ticks < 1) ticks = 1;
188 }
189 else // otherwise call EventLoop again with 0 timemout
190 ticks = 0;
191
192 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
193 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond;
194
195 (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData);
196
197 if (sigismember(&signals, SIGHUP )) Reconfigure(m);
198 if (sigismember(&signals, SIGUSR1)) DumpStateLog(m);
199 // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up.
200 if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring");
201 if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break;
202 }
203 return EINTR;
204 }
205
206 int main(int argc, char **argv)
207 {
208 mStatus err;
209
210 ParseCmdLinArgs(argc, argv);
211
212 LogMsgIdent(mDNSResponderVersionString, "starting");
213
214 err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses,
215 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
216
217 if (mStatus_NoError == err)
218 err = udsserver_init(dnssd_InvalidSocket);
219
220 Reconfigure(&mDNSStorage);
221
222 // Now that we're finished with anything privileged, switch over to running as "nobody"
223 if (mStatus_NoError == err)
224 {
225 const struct passwd *pw = getpwnam("nobody");
226 if (pw != NULL)
227 setuid(pw->pw_uid);
228 else
229 LogMsg("WARNING: mdnsd continuing as root because user \"nobody\" does not exist");
230 }
231
232 if (mStatus_NoError == err)
233 err = MainLoop(&mDNSStorage);
234
235 LogMsgIdent(mDNSResponderVersionString, "stopping");
236
237 mDNS_Close(&mDNSStorage);
238
239 if (udsserver_exit(dnssd_InvalidSocket) < 0)
240 LogMsg("ExitCallback: udsserver_exit failed");
241
242 #if MDNS_DEBUGMSGS > 0
243 printf("mDNSResponder exiting normally with %ld\n", err);
244 #endif
245
246 return err;
247 }
248
249 // uds_daemon support ////////////////////////////////////////////////////////////
250
251 mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context)
252 /* Support routine for uds_daemon.c */
253 {
254 // Depends on the fact that udsEventCallback == mDNSPosixEventCallback
255 return mDNSPosixAddFDToEventLoop(fd, callback, context);
256 }
257
258 mStatus udsSupportRemoveFDFromEventLoop(int fd) // Note: This also CLOSES the file descriptor
259 {
260 mStatus err = mDNSPosixRemoveFDFromEventLoop(fd);
261 close(fd);
262 return err;
263 }
264
265 mDNSexport void RecordUpdatedNiceLabel(mDNS *const m, mDNSs32 delay)
266 {
267 (void)m;
268 (void)delay;
269 // No-op, for now
270 }
271
272 // If the process crashes, then this string will be magically included in the automatically-generated crash log
273 const char *__crashreporter_info__ = mDNSResponderVersionString_SCCS + 5;
274 asm(".desc ___crashreporter_info__, 0x10");
275
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