2 * Copyright (c) 2003-2019 Apple Inc. All rights reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 Contains: main & associated Application layer for mDNSResponder on Linux.
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
38 #include <sys/types.h>
39 #include <sys/socket.h>
43 extern int daemon(int, int);
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()
53 #define CONFIG_FILE "/etc/mdnsd.conf"
54 static domainname DynDNSZone
; // Default wide-area zone for service registration
55 static domainname DynDNSHostname
;
57 #define RR_CACHE_SIZE 500
58 static CacheEntity gRRCache
[RR_CACHE_SIZE
];
59 static mDNS_PlatformSupport PlatformStorage
;
61 mDNSlocal
void mDNS_StatusCallback(mDNS
*const m
, mStatus result
)
64 if (result
== mStatus_NoError
)
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.
72 else if (result
== mStatus_ConfigChanged
)
74 udsserver_handle_configchange(m
);
76 else if (result
== mStatus_GrowCache
)
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
);
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
88 static void Reconfigure(mDNS
*m
)
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
);
102 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy.
103 mDNSlocal
void ParseCmdLinArgs(int argc
, char **argv
)
107 if (0 == strcmp(argv
[1], "-debug")) mDNS_DebugMode
= mDNStrue
;
108 else printf("Usage: %s [-debug]\n", argv
[0]);
113 int result
= daemon(0, 0);
114 if (result
!= 0) { LogMsg("Could not run as daemon - exiting"); exit(result
); }
116 LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting");
122 mDNSlocal
void DumpStateLog()
123 // Dump a little log of what we've been up to.
125 char timestamp
[64]; // 64 is enough to store the UTC timestmp
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;
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
);
134 udsserver_info_dump_to_fd(STDERR_FILENO
);
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
);
140 mDNSlocal mStatus
MainLoop(mDNS
*m
) // Loop until we quit.
143 mDNSBool gotData
= mDNSfalse
;
145 mDNSPosixListenForSignalInEventLoop(SIGINT
);
146 mDNSPosixListenForSignalInEventLoop(SIGTERM
);
147 mDNSPosixListenForSignalInEventLoop(SIGUSR1
);
148 mDNSPosixListenForSignalInEventLoop(SIGPIPE
);
149 mDNSPosixListenForSignalInEventLoop(SIGHUP
) ;
153 // Work out how long we expect to sleep before the next scheduled task
154 struct timeval timeout
;
157 // Only idle if we didn't find any data the last time around
160 mDNSs32 nextTimerEvent
= mDNS_Execute(m
);
161 nextTimerEvent
= udsserver_idle(nextTimerEvent
);
162 ticks
= nextTimerEvent
- mDNS_TimeNow(m
);
163 if (ticks
< 1) ticks
= 1;
165 else // otherwise call EventLoop again with 0 timemout
168 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
169 timeout
.tv_usec
= (ticks
% mDNSPlatformOneSecond
) * 1000000 / mDNSPlatformOneSecond
;
171 (void) mDNSPosixRunEventLoopOnce(m
, &timeout
, &signals
, &gotData
);
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;
182 int main(int argc
, char **argv
)
186 ParseCmdLinArgs(argc
, argv
);
188 LogMsg("%s starting", mDNSResponderVersionString
);
190 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
, gRRCache
, RR_CACHE_SIZE
, mDNS_Init_AdvertiseLocalAddresses
,
191 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
193 if (mStatus_NoError
== err
)
194 err
= udsserver_init(mDNSNULL
, 0);
196 Reconfigure(&mDNSStorage
);
198 // Now that we're finished with anything privileged, switch over to running as "nobody"
199 if (mStatus_NoError
== err
)
201 const struct passwd
*pw
= getpwnam("nobody");
204 if (setgid(pw
->pw_gid
) < 0)
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
));
209 if (setuid(pw
->pw_uid
) < 0)
211 LogMsg("WARNING: mdnsd continuing as root because setuid to \"nobody\" failed with %s", strerror(errno
));
216 LogMsg("WARNING: mdnsd continuing as root because user \"nobody\" does not exist");
220 if (mStatus_NoError
== err
)
221 err
= MainLoop(&mDNSStorage
);
223 LogMsg("%s stopping", mDNSResponderVersionString
);
225 mDNS_Close(&mDNSStorage
);
227 if (udsserver_exit() < 0)
228 LogMsg("ExitCallback: udsserver_exit failed");
230 #if MDNS_DEBUGMSGS > 0
231 printf("mDNSResponder exiting normally with %d\n", err
);
237 // uds_daemon support ////////////////////////////////////////////////////////////
239 mStatus
udsSupportAddFDToEventLoop(int fd
, udsEventCallback callback
, void *context
, void **platform_data
)
240 /* Support routine for uds_daemon.c */
242 // Depends on the fact that udsEventCallback == mDNSPosixEventCallback
243 (void) platform_data
;
244 return mDNSPosixAddFDToEventLoop(fd
, callback
, context
);
247 int udsSupportReadFD(dnssd_sock_t fd
, char *buf
, int len
, int flags
, void *platform_data
)
249 (void) platform_data
;
250 return recv(fd
, buf
, len
, flags
);
253 mStatus
udsSupportRemoveFDFromEventLoop(int fd
, void *platform_data
) // Note: This also CLOSES the file descriptor
255 mStatus err
= mDNSPosixRemoveFDFromEventLoop(fd
);
256 (void) platform_data
;
261 mDNSexport
void RecordUpdatedNiceLabel(mDNSs32 delay
)
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");
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)";
279 mDNSexport
const char mDNSResponderVersionString_SCCS
[] = "@(#) mDNSResponder (Engineering Build) (" __DATE__
" " __TIME__
")";