Home | History | Annotate | Line # | Download | only in mDNSPosix
PosixDaemon.c revision 1.17
      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 #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 "DNSCommon.h"
     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 
     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 
     92 static void Reconfigure(mDNS *m)
     93 {
     94     mDNSAddr DynDNSIP;
     95     const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 198, 51, 100, 42 } } } };;
     96     mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL);
     97     mDNS_Lock(m);
     98     if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0)
     99         LogInfo("Unable to parse DNS server list. Unicast DNS-SD unavailable");
    100     mDNS_Unlock(m);
    101     ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL);
    102     mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy);
    103     if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL);
    104     if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL);
    105     mDNS_ConfigChanged(m);
    106 }
    107 
    108 // Do appropriate things at startup with command line arguments. Calls exit() if unhappy.
    109 mDNSlocal void ParseCmdLinArgs(int argc, char **argv)
    110 {
    111     if (argc > 1)
    112     {
    113         if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue;
    114         else printf("Usage: %s [-debug]\n", argv[0]);
    115     }
    116 
    117     if (!mDNS_DebugMode)
    118     {
    119         int result = daemon(0, 0);
    120         if (result != 0) { LogMsg("Could not run as daemon - exiting"); exit(result); }
    121 #if __APPLE__
    122         LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting");
    123         exit(-1);
    124 #endif
    125     }
    126 }
    127 
    128 mDNSlocal void DumpStateLog()
    129 // Dump a little log of what we've been up to.
    130 {
    131     LogMsg("---- BEGIN STATE LOG ----");
    132     udsserver_info();
    133     LogMsg("----  END STATE LOG  ----");
    134 }
    135 
    136 mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit.
    137 {
    138     sigset_t signals;
    139     mDNSBool gotData = mDNSfalse;
    140 
    141     mDNSPosixListenForSignalInEventLoop(SIGINT);
    142     mDNSPosixListenForSignalInEventLoop(SIGTERM);
    143     mDNSPosixListenForSignalInEventLoop(SIGUSR1);
    144     mDNSPosixListenForSignalInEventLoop(SIGPIPE);
    145     mDNSPosixListenForSignalInEventLoop(SIGHUP) ;
    146 
    147     for (; ;)
    148     {
    149         // Work out how long we expect to sleep before the next scheduled task
    150         struct timeval timeout;
    151         mDNSs32 ticks;
    152 
    153         // Only idle if we didn't find any data the last time around
    154         if (!gotData)
    155         {
    156             mDNSs32 nextTimerEvent = mDNS_Execute(m);
    157             nextTimerEvent = udsserver_idle(nextTimerEvent);
    158             ticks = nextTimerEvent - mDNS_TimeNow(m);
    159             if (ticks < 1) ticks = 1;
    160         }
    161         else    // otherwise call EventLoop again with 0 timemout
    162             ticks = 0;
    163 
    164         timeout.tv_sec = ticks / mDNSPlatformOneSecond;
    165         timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond;
    166 
    167         (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData);
    168 
    169         if (sigismember(&signals, SIGHUP )) Reconfigure(m);
    170         if (sigismember(&signals, SIGUSR1)) DumpStateLog();
    171         // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up.
    172         if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring");
    173         if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break;
    174     }
    175     return EINTR;
    176 }
    177 
    178 int main(int argc, char **argv)
    179 {
    180     mStatus err;
    181 
    182     ParseCmdLinArgs(argc, argv);
    183 
    184     LogInfo("%s starting", mDNSResponderVersionString);
    185 
    186     err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses,
    187                     mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
    188 
    189     if (mStatus_NoError == err)
    190         err = udsserver_init(mDNSNULL, 0);
    191 
    192     Reconfigure(&mDNSStorage);
    193 
    194     // Now that we're finished with anything privileged, switch over to running as "nobody"
    195     if (mStatus_NoError == err)
    196     {
    197         const struct passwd *pw = getpwnam(MDNSD_USER);
    198         if (pw != NULL)
    199         {
    200             setgid(pw->pw_gid);
    201             setuid(pw->pw_uid);
    202         }
    203         else
    204 #ifdef MDNSD_NOROOT
    205         {
    206             LogMsg("WARNING: mdnsd exiting because user \""MDNSD_USER"\" does not exist");
    207             err = mStatus_Invalid;
    208         }
    209 #else
    210             LogMsg("WARNING: mdnsd continuing as root because user \""MDNSD_USER"\" does not exist");
    211 #endif
    212     }
    213 
    214     if (mStatus_NoError == err)
    215         err = MainLoop(&mDNSStorage);
    216 
    217     LogInfo("%s stopping", mDNSResponderVersionString);
    218 
    219     mDNS_Close(&mDNSStorage);
    220 
    221     if (udsserver_exit() < 0)
    222         LogMsg("ExitCallback: udsserver_exit failed");
    223 
    224  #if MDNS_DEBUGMSGS > 0
    225     printf("mDNSResponder exiting normally with %ld\n", err);
    226  #endif
    227 
    228     return err;
    229 }
    230 
    231 //		uds_daemon support		////////////////////////////////////////////////////////////
    232 
    233 mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
    234 /* Support routine for uds_daemon.c */
    235 {
    236     // Depends on the fact that udsEventCallback == mDNSPosixEventCallback
    237     (void) platform_data;
    238     return mDNSPosixAddFDToEventLoop(fd, callback, context);
    239 }
    240 
    241 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
    242 {
    243     (void) platform_data;
    244     return recv(fd, buf, len, flags);
    245 }
    246 
    247 mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data)        // Note: This also CLOSES the file descriptor
    248 {
    249     mStatus err = mDNSPosixRemoveFDFromEventLoop(fd);
    250     (void) platform_data;
    251     close(fd);
    252     return err;
    253 }
    254 
    255 mDNSexport void RecordUpdatedNiceLabel(mDNSs32 delay)
    256 {
    257     (void)delay;
    258     // No-op, for now
    259 }
    260 
    261 #if _BUILDING_XCODE_PROJECT_
    262 // If the process crashes, then this string will be magically included in the automatically-generated crash log
    263 const char *__crashreporter_info__ = mDNSResponderVersionString_SCCS + 5;
    264 asm (".desc ___crashreporter_info__, 0x10");
    265 #endif
    266 
    267 // For convenience when using the "strings" command, this is the last thing in the file
    268 #if mDNSResponderVersion > 1
    269 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder-" STRINGIFY(mDNSResponderVersion)
    270 #ifndef MDNS_VERSIONSTR_NODTS
    271     " (" __DATE__ " " __TIME__ ")"
    272 #endif
    273 ;
    274 #else
    275 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)"
    276 #ifndef MDNS_VERSIONSTR_NODTS
    277     " (" __DATE__ " " __TIME__ ")"
    278 #endif
    279 ;
    280 #endif
    281