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