]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSPosix/PosixDaemon.c
mDNSResponder-1096.0.2.tar.gz
[apple/mdnsresponder.git] / mDNSPosix / PosixDaemon.c
1 /*
2 * Copyright (c) 2003-2019 Apple Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15
16 File: daemon.c
17
18 Contains: main & associated Application layer for mDNSResponder on Linux.
19
20 */
21
22 #if __APPLE__
23 // In Mac OS X 10.5 and later trying to use the daemon function gives a “‘daemon’ is deprecated”
24 // error, which prevents compilation because we build with "-Werror".
25 // Since this is supposed to be portable cross-platform code, we don't care that daemon is
26 // deprecated on Mac OS X 10.5, so we use this preprocessor trick to eliminate the error message.
27 #define daemon yes_we_know_that_daemon_is_deprecated_in_os_x_10_5_thankyou
28 #endif
29
30 #include <stdio.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #include <signal.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <pwd.h>
38 #include <sys/types.h>
39 #include <sys/socket.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 "PlatformCommon.h"
51 #include "posix_utilities.h" // For getLocalTimestamp()
52
53 #define CONFIG_FILE "/etc/mdnsd.conf"
54 static domainname DynDNSZone; // Default wide-area zone for service registration
55 static domainname DynDNSHostname;
56
57 #define RR_CACHE_SIZE 500
58 static CacheEntity gRRCache[RR_CACHE_SIZE];
59 static mDNS_PlatformSupport PlatformStorage;
60
61 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
62 {
63 (void)m; // Unused
64 if (result == mStatus_NoError)
65 {
66 // On successful registration of dot-local mDNS host name, daemon may want to check if
67 // any name conflict and automatic renaming took place, and if so, record the newly negotiated
68 // name in persistent storage for next time. It should also inform the user of the name change.
69 // On Mac OS X we store the current dot-local mDNS host name in the SCPreferences store,
70 // and notify the user with a CFUserNotification.
71 }
72 else if (result == mStatus_ConfigChanged)
73 {
74 udsserver_handle_configchange(m);
75 }
76 else if (result == mStatus_GrowCache)
77 {
78 // Allocate another chunk of cache storage
79 CacheEntity *storage = malloc(sizeof(CacheEntity) * RR_CACHE_SIZE);
80 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
81 }
82 }
83
84 // %%% Reconfigure() probably belongs in the platform support layer (mDNSPosix.c), not the daemon cde
85 // -- all client layers running on top of mDNSPosix.c need to handle network configuration changes,
86 // not only the Unix Domain Socket Daemon
87
88 static void Reconfigure(mDNS *m)
89 {
90 mDNSAddr DynDNSIP;
91 const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 1, 1, 1, 1 } } } };;
92 mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL);
93 if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0)
94 LogMsg("Unable to parse DNS server list. Unicast DNS-SD unavailable");
95 ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL);
96 mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy);
97 if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL);
98 if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL);
99 mDNS_ConfigChanged(m);
100 }
101
102 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy.
103 mDNSlocal void ParseCmdLinArgs(int argc, char **argv)
104 {
105 if (argc > 1)
106 {
107 if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue;
108 else printf("Usage: %s [-debug]\n", argv[0]);
109 }
110
111 if (!mDNS_DebugMode)
112 {
113 int result = daemon(0, 0);
114 if (result != 0) { LogMsg("Could not run as daemon - exiting"); exit(result); }
115 #if __APPLE__
116 LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting");
117 exit(-1);
118 #endif
119 }
120 }
121
122 mDNSlocal void DumpStateLog()
123 // Dump a little log of what we've been up to.
124 {
125 char timestamp[64]; // 64 is enough to store the UTC timestmp
126
127 mDNSu32 major_version = _DNS_SD_H / 10000;
128 mDNSu32 minor_version1 = (_DNS_SD_H - major_version * 10000) / 100;
129 mDNSu32 minor_version2 = _DNS_SD_H % 100;
130
131 getLocalTimestamp(timestamp, sizeof(timestamp));
132 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- BEGIN STATE LOG ---- (%s mDNSResponder Build %d.%02d.%02d)", timestamp, major_version, minor_version1, minor_version2);
133
134 udsserver_info_dump_to_fd(STDERR_FILENO);
135
136 getLocalTimestamp(timestamp, sizeof(timestamp));
137 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- END STATE LOG ---- (%s mDNSResponder Build %d.%02d.%02d)", timestamp, major_version, minor_version1, minor_version2);
138 }
139
140 mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit.
141 {
142 sigset_t signals;
143 mDNSBool gotData = mDNSfalse;
144
145 mDNSPosixListenForSignalInEventLoop(SIGINT);
146 mDNSPosixListenForSignalInEventLoop(SIGTERM);
147 mDNSPosixListenForSignalInEventLoop(SIGUSR1);
148 mDNSPosixListenForSignalInEventLoop(SIGPIPE);
149 mDNSPosixListenForSignalInEventLoop(SIGHUP) ;
150
151 for (; ;)
152 {
153 // Work out how long we expect to sleep before the next scheduled task
154 struct timeval timeout;
155 mDNSs32 ticks;
156
157 // Only idle if we didn't find any data the last time around
158 if (!gotData)
159 {
160 mDNSs32 nextTimerEvent = mDNS_Execute(m);
161 nextTimerEvent = udsserver_idle(nextTimerEvent);
162 ticks = nextTimerEvent - mDNS_TimeNow(m);
163 if (ticks < 1) ticks = 1;
164 }
165 else // otherwise call EventLoop again with 0 timemout
166 ticks = 0;
167
168 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
169 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond;
170
171 (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData);
172
173 if (sigismember(&signals, SIGHUP )) Reconfigure(m);
174 if (sigismember(&signals, SIGUSR1)) DumpStateLog();
175 // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up.
176 if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring");
177 if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break;
178 }
179 return EINTR;
180 }
181
182 int main(int argc, char **argv)
183 {
184 mStatus err;
185
186 ParseCmdLinArgs(argc, argv);
187
188 LogMsg("%s starting", mDNSResponderVersionString);
189
190 err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses,
191 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
192
193 if (mStatus_NoError == err)
194 err = udsserver_init(mDNSNULL, 0);
195
196 Reconfigure(&mDNSStorage);
197
198 // Now that we're finished with anything privileged, switch over to running as "nobody"
199 if (mStatus_NoError == err)
200 {
201 const struct passwd *pw = getpwnam("nobody");
202 if (pw != NULL)
203 {
204 if (setgid(pw->pw_gid) < 0)
205 {
206 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
207 "WARNING: mdnsd continuing as group root because setgid to \"nobody\" failed with " PUB_S, strerror(errno));
208 }
209 if (setuid(pw->pw_uid) < 0)
210 {
211 LogMsg("WARNING: mdnsd continuing as root because setuid to \"nobody\" failed with %s", strerror(errno));
212 }
213 }
214 else
215 {
216 LogMsg("WARNING: mdnsd continuing as root because user \"nobody\" does not exist");
217 }
218 }
219
220 if (mStatus_NoError == err)
221 err = MainLoop(&mDNSStorage);
222
223 LogMsg("%s stopping", mDNSResponderVersionString);
224
225 mDNS_Close(&mDNSStorage);
226
227 if (udsserver_exit() < 0)
228 LogMsg("ExitCallback: udsserver_exit failed");
229
230 #if MDNS_DEBUGMSGS > 0
231 printf("mDNSResponder exiting normally with %d\n", err);
232 #endif
233
234 return err;
235 }
236
237 // uds_daemon support ////////////////////////////////////////////////////////////
238
239 mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
240 /* Support routine for uds_daemon.c */
241 {
242 // Depends on the fact that udsEventCallback == mDNSPosixEventCallback
243 (void) platform_data;
244 return mDNSPosixAddFDToEventLoop(fd, callback, context);
245 }
246
247 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
248 {
249 (void) platform_data;
250 return recv(fd, buf, len, flags);
251 }
252
253 mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor
254 {
255 mStatus err = mDNSPosixRemoveFDFromEventLoop(fd);
256 (void) platform_data;
257 close(fd);
258 return err;
259 }
260
261 mDNSexport void RecordUpdatedNiceLabel(mDNSs32 delay)
262 {
263 (void)delay;
264 // No-op, for now
265 }
266
267 #if _BUILDING_XCODE_PROJECT_
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 #endif
272
273 // For convenience when using the "strings" command, this is the last thing in the file
274 #if mDNSResponderVersion > 1
275 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder-" STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
276 #elif MDNS_VERSIONSTR_NODTS
277 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)";
278 #else
279 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build) (" __DATE__ " " __TIME__ ")";
280 #endif