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