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