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 #ifdef __ANDROID__
42 #include "cutils/sockets.h"
43 #endif
44
45 #if __APPLE__
46 #undef daemon
47 extern int daemon(int, int);
48 #endif
49
50 #include "mDNSEmbeddedAPI.h"
51 #include "mDNSPosix.h"
52 #include "mDNSUNP.h" // For daemon()
53 #include "uds_daemon.h"
54 #include "PlatformCommon.h"
55
56 #ifndef MDNS_USERNAME
57 #define MDNS_USERNAME "nobody"
58 #endif
59
60 #define CONFIG_FILE "/etc/mdnsd.conf"
61 static domainname DynDNSZone; // Default wide-area zone for service registration
62 static domainname DynDNSHostname;
63
64 #define RR_CACHE_SIZE 500
65 static CacheEntity gRRCache[RR_CACHE_SIZE];
66 static mDNS_PlatformSupport PlatformStorage;
67
mDNS_StatusCallback(mDNS * const m,mStatus result)68 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
69 {
70 (void)m; // Unused
71 if (result == mStatus_NoError)
72 {
73 // On successful registration of dot-local mDNS host name, daemon may want to check if
74 // any name conflict and automatic renaming took place, and if so, record the newly negotiated
75 // name in persistent storage for next time. It should also inform the user of the name change.
76 // On Mac OS X we store the current dot-local mDNS host name in the SCPreferences store,
77 // and notify the user with a CFUserNotification.
78 }
79 else if (result == mStatus_ConfigChanged)
80 {
81 udsserver_handle_configchange(m);
82 }
83 else if (result == mStatus_GrowCache)
84 {
85 // Allocate another chunk of cache storage
86 CacheEntity *storage = malloc(sizeof(CacheEntity) * RR_CACHE_SIZE);
87 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
88 }
89 }
90
91 // %%% Reconfigure() probably belongs in the platform support layer (mDNSPosix.c), not the daemon cde
92 // -- all client layers running on top of mDNSPosix.c need to handle network configuration changes,
93 // not only the Unix Domain Socket Daemon
94
Reconfigure(mDNS * m)95 static void Reconfigure(mDNS *m)
96 {
97 mDNSAddr DynDNSIP;
98 const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 1, 1, 1, 1 } } } };;
99 mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL);
100 if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0)
101 LogMsg("Unable to parse DNS server list. Unicast DNS-SD unavailable");
102 ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL);
103 mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy);
104 if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL);
105 if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL);
106 mDNS_ConfigChanged(m);
107 }
108
109 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy.
ParseCmdLinArgs(int argc,char ** argv)110 mDNSlocal void ParseCmdLinArgs(int argc, char **argv)
111 {
112 if (argc > 1)
113 {
114 if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue;
115 else printf("Usage: %s [-debug]\n", argv[0]);
116 }
117 #ifndef __ANDROID__
118 if (!mDNS_DebugMode)
119 {
120 int result = daemon(0, 0);
121 if (result != 0) { LogMsg("Could not run as daemon - exiting"); exit(result); }
122 #if __APPLE__
123 LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting");
124 exit(-1);
125 #endif
126 }
127 #endif // !__ANDROID__
128 }
129
DumpStateLog(mDNS * const m)130 mDNSlocal void DumpStateLog(mDNS *const m)
131 // Dump a little log of what we've been up to.
132 {
133 LogMsg("---- BEGIN STATE LOG ----");
134 udsserver_info(m);
135 LogMsg("---- END STATE LOG ----");
136 }
137
MainLoop(mDNS * m)138 mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit.
139 {
140 sigset_t signals;
141 mDNSBool gotData = mDNSfalse;
142
143 mDNSPosixListenForSignalInEventLoop(SIGINT);
144 mDNSPosixListenForSignalInEventLoop(SIGTERM);
145 mDNSPosixListenForSignalInEventLoop(SIGUSR1);
146 mDNSPosixListenForSignalInEventLoop(SIGPIPE);
147 mDNSPosixListenForSignalInEventLoop(SIGHUP) ;
148
149 for (; ;)
150 {
151 // Work out how long we expect to sleep before the next scheduled task
152 struct timeval timeout;
153 mDNSs32 ticks;
154
155 // Only idle if we didn't find any data the last time around
156 if (!gotData)
157 {
158 mDNSs32 nextTimerEvent = mDNS_Execute(m);
159 nextTimerEvent = udsserver_idle(nextTimerEvent);
160 ticks = nextTimerEvent - mDNS_TimeNow(m);
161 if (ticks < 1) ticks = 1;
162 }
163 else // otherwise call EventLoop again with 0 timemout
164 ticks = 0;
165
166 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
167 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond;
168
169 (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData);
170
171 if (sigismember(&signals, SIGHUP )) Reconfigure(m);
172 if (sigismember(&signals, SIGUSR1)) DumpStateLog(m);
173 // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up.
174 if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring");
175 if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break;
176 }
177 return EINTR;
178 }
179
main(int argc,char ** argv)180 int main(int argc, char **argv)
181 {
182 mStatus err;
183
184 ParseCmdLinArgs(argc, argv);
185
186 LogMsg("%s starting", mDNSResponderVersionString);
187
188 err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses,
189 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
190
191 if (mStatus_NoError == err)
192 #ifdef __ANDROID__
193 {
194 dnssd_sock_t s[1];
195 char *socketname = strrchr(MDNS_UDS_SERVERPATH, '/');
196 if (socketname)
197 {
198 socketname++; // skip '/'
199 s[0] = android_get_control_socket(socketname);
200 err = udsserver_init(s, 1);
201 } else {
202 err = udsserver_init(mDNSNULL, 0);
203 }
204 }
205 #else
206 err = udsserver_init(mDNSNULL, 0);
207 #endif // __ANDROID__
208
209 Reconfigure(&mDNSStorage);
210
211 // Now that we're finished with anything privileged, switch over to running as "nobody"
212 if (mStatus_NoError == err)
213 {
214 const struct passwd *pw = getpwnam(MDNS_USERNAME);
215 if (pw != NULL)
216 setuid(pw->pw_uid);
217 else
218 LogMsg("WARNING: mdnsd continuing as root because user \"%s\" does not exist", MDNS_USERNAME);
219 }
220
221 if (mStatus_NoError == err)
222 err = MainLoop(&mDNSStorage);
223
224 LogMsg("%s stopping", mDNSResponderVersionString);
225
226 mDNS_Close(&mDNSStorage);
227
228 if (udsserver_exit() < 0)
229 LogMsg("ExitCallback: udsserver_exit failed");
230
231 #if MDNS_DEBUGMSGS > 0
232 printf("mDNSResponder exiting normally with %ld\n", err);
233 #endif
234
235 return err;
236 }
237
238 // uds_daemon support ////////////////////////////////////////////////////////////
239
udsSupportAddFDToEventLoop(int fd,udsEventCallback callback,void * context,void ** platform_data)240 mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
241 /* Support routine for uds_daemon.c */
242 {
243 // Depends on the fact that udsEventCallback == mDNSPosixEventCallback
244 (void) platform_data;
245 return mDNSPosixAddFDToEventLoop(fd, callback, context);
246 }
247
udsSupportReadFD(dnssd_sock_t fd,char * buf,int len,int flags,void * platform_data)248 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
249 {
250 (void) platform_data;
251 return recv(fd, buf, len, flags);
252 }
253
udsSupportRemoveFDFromEventLoop(int fd,void * platform_data)254 mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor
255 {
256 mStatus err = mDNSPosixRemoveFDFromEventLoop(fd);
257 (void) platform_data;
258 close(fd);
259 return err;
260 }
261
RecordUpdatedNiceLabel(mDNS * const m,mDNSs32 delay)262 mDNSexport void RecordUpdatedNiceLabel(mDNS *const m, mDNSs32 delay)
263 {
264 (void)m;
265 (void)delay;
266 // No-op, for now
267 }
268
269 #if _BUILDING_XCODE_PROJECT_
270 // If the process crashes, then this string will be magically included in the automatically-generated crash log
271 const char *__crashreporter_info__ = mDNSResponderVersionString_SCCS + 5;
272 asm(".desc ___crashreporter_info__, 0x10");
273 #endif
274
275 // For convenience when using the "strings" command, this is the last thing in the file
276 #if mDNSResponderVersion > 1
277 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder-" STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
278 #elif MDNS_VERSIONSTR_NODTS
279 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)";
280 #else
281 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build) (" __DATE__ " " __TIME__ ")";
282 #endif
283