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