xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSShared/PlatformCommon.c (revision 8a2b682e57a046b828f37bcde1776f131ef4629f)
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2004-2015 Apple 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 
18 #include <stdio.h>              // Needed for fopen() etc.
19 #include <unistd.h>             // Needed for close()
20 #include <string.h>             // Needed for strlen() etc.
21 #include <errno.h>              // Needed for errno etc.
22 #include <sys/socket.h>         // Needed for socket() etc.
23 #include <netinet/in.h>         // Needed for sockaddr_in
24 #include <syslog.h>
25 
26 #if APPLE_OSX_mDNSResponder
27 #include <os/log.h>
28 #endif
29 
30 #include "mDNSEmbeddedAPI.h"    // Defines the interface provided to the client layer above
31 #include "DNSCommon.h"
32 #include "PlatformCommon.h"
33 
34 #ifdef NOT_HAVE_SOCKLEN_T
35 typedef unsigned int socklen_t;
36 #endif
37 
38 // Bind a UDP socket to find the source address to a destination
39 mDNSexport void mDNSPlatformSourceAddrForDest(mDNSAddr *const src, const mDNSAddr *const dst)
40 {
41     union { struct sockaddr s; struct sockaddr_in a4; struct sockaddr_in6 a6; } addr;
42     socklen_t len = sizeof(addr);
43     socklen_t inner_len = 0;
44     int sock = socket(AF_INET, SOCK_DGRAM, 0);
45     src->type = mDNSAddrType_None;
46     if (sock == -1) return;
47     if (dst->type == mDNSAddrType_IPv4)
48     {
49         inner_len = sizeof(addr.a4);
50         #ifndef NOT_HAVE_SA_LEN
51         addr.a4.sin_len         = inner_len;
52         #endif
53         addr.a4.sin_family      = AF_INET;
54         addr.a4.sin_port        = 1;    // Not important, any port will do
55         addr.a4.sin_addr.s_addr = dst->ip.v4.NotAnInteger;
56     }
57     else if (dst->type == mDNSAddrType_IPv6)
58     {
59         inner_len = sizeof(addr.a6);
60         #ifndef NOT_HAVE_SA_LEN
61         addr.a6.sin6_len      = inner_len;
62         #endif
63         addr.a6.sin6_family   = AF_INET6;
64         addr.a6.sin6_flowinfo = 0;
65         addr.a6.sin6_port     = 1;  // Not important, any port will do
66         addr.a6.sin6_addr     = *(struct in6_addr*)&dst->ip.v6;
67         addr.a6.sin6_scope_id = 0;
68     }
69     else return;
70 
71     if ((connect(sock, &addr.s, inner_len)) < 0) {
72 	if (errno != ENETUNREACH) {
73 	    LogMsg("mDNSPlatformSourceAddrForDest: connect %#a failed errno %d "
74 		"(%s)", dst, errno, strerror(errno));
75 	}
76 	goto exit;
77     }
78 
79     if ((getsockname(sock, &addr.s, &len)) < 0)
80     { LogMsg("mDNSPlatformSourceAddrForDest: getsockname failed errno %d (%s)", errno, strerror(errno)); goto exit; }
81 
82     src->type = dst->type;
83     if (dst->type == mDNSAddrType_IPv4) src->ip.v4.NotAnInteger = addr.a4.sin_addr.s_addr;
84     else src->ip.v6 = *(mDNSv6Addr*)&addr.a6.sin6_addr;
85 exit:
86     close(sock);
87 }
88 
89 // dst must be at least MAX_ESCAPED_DOMAIN_NAME bytes, and option must be less than 32 bytes in length
90 mDNSlocal mDNSBool GetConfigOption(char *dst, const char *option, FILE *f)
91 {
92     char buf[32+1+MAX_ESCAPED_DOMAIN_NAME]; // Option name, one space, option value
93     unsigned int len = strlen(option);
94     if (len + 1 + MAX_ESCAPED_DOMAIN_NAME > sizeof(buf)-1) { LogMsg("GetConfigOption: option %s too long", option); return mDNSfalse; }
95     fseek(f, 0, SEEK_SET);  // set position to beginning of stream
96     while (fgets(buf, sizeof(buf), f))      // Read at most sizeof(buf)-1 bytes from file, and append '\0' C-string terminator
97     {
98         if (!strncmp(buf, option, len))
99         {
100             strncpy(dst, buf + len + 1, MAX_ESCAPED_DOMAIN_NAME-1);
101             if (dst[MAX_ESCAPED_DOMAIN_NAME-1]) dst[MAX_ESCAPED_DOMAIN_NAME-1] = '\0';
102             len = strlen(dst);
103             if (len && dst[len-1] == '\n') dst[len-1] = '\0';  // chop newline
104             return mDNStrue;
105         }
106     }
107     debugf("Option %s not set", option);
108     return mDNSfalse;
109 }
110 
111 mDNSexport void ReadDDNSSettingsFromConfFile(mDNS *const m, const char *const filename, domainname *const hostname, domainname *const domain, mDNSBool *DomainDiscoveryDisabled)
112 {
113     char buf[MAX_ESCAPED_DOMAIN_NAME] = "";
114     mStatus err;
115     FILE *f = fopen(filename, "r");
116 
117     if (hostname) hostname->c[0] = 0;
118     if (domain) domain->c[0] = 0;
119     if (DomainDiscoveryDisabled) *DomainDiscoveryDisabled = mDNSfalse;
120 
121     if (f)
122     {
123         if (DomainDiscoveryDisabled && GetConfigOption(buf, "DomainDiscoveryDisabled", f) && !strcasecmp(buf, "true")) *DomainDiscoveryDisabled = mDNStrue;
124         if (hostname && GetConfigOption(buf, "hostname", f) && !MakeDomainNameFromDNSNameString(hostname, buf)) goto badf;
125         if (domain && GetConfigOption(buf, "zone", f) && !MakeDomainNameFromDNSNameString(domain, buf)) goto badf;
126         buf[0] = 0;
127         GetConfigOption(buf, "secret-64", f);  // failure means no authentication
128         fclose(f);
129         f = NULL;
130     }
131     else
132     {
133         if (errno != ENOENT) LogMsg("ERROR: Config file exists, but cannot be opened.");
134         return;
135     }
136 
137     if (domain && domain->c[0] && buf[0])
138     {
139         DomainAuthInfo *info = (DomainAuthInfo*)mDNSPlatformMemAllocate(sizeof(*info));
140         // for now we assume keyname = service reg domain and we use same key for service and hostname registration
141         err = mDNS_SetSecretForDomain(m, info, domain, domain, buf, NULL, 0, mDNSfalse);
142         if (err) LogMsg("ERROR: mDNS_SetSecretForDomain returned %d for domain %##s", err, domain->c);
143     }
144 
145     return;
146 
147 badf:
148     LogMsg("ERROR: malformatted config file");
149     if (f) fclose(f);
150 }
151 
152 #if MDNS_DEBUGMSGS
153 mDNSexport void mDNSPlatformWriteDebugMsg(const char *msg)
154 {
155     fprintf(stderr,"%s\n", msg);
156     fflush(stderr);
157 }
158 #endif
159 
160 mDNSexport void mDNSPlatformWriteLogMsg(const char *ident, const char *buffer, mDNSLogLevel_t loglevel)
161 {
162 #if APPLE_OSX_mDNSResponder && LogTimeStamps
163     extern mDNS mDNSStorage;
164     extern mDNSu32 mDNSPlatformClockDivisor;
165     mDNSs32 t = mDNSStorage.timenow ? mDNSStorage.timenow : mDNSPlatformClockDivisor ? mDNS_TimeNow_NoLock(&mDNSStorage) : 0;
166     int ms = ((t < 0) ? -t : t) % 1000;
167 #endif
168 
169     if (mDNS_DebugMode) // In debug mode we write to stderr
170     {
171 #if APPLE_OSX_mDNSResponder && LogTimeStamps
172         if (ident && ident[0] && mDNSPlatformClockDivisor)
173             fprintf(stderr,"%8d.%03d: %s\n", (int)(t/1000), ms, buffer);
174         else
175 #endif
176         fprintf(stderr,"%s\n", buffer);
177         fflush(stderr);
178     }
179     else                // else, in production mode, we write to syslog
180     {
181         static int log_inited = 0;
182 
183         int syslog_level = LOG_ERR;
184         switch (loglevel)
185         {
186 #if APPLE_OSX_mDNSResponder
187         case MDNS_LOG_MSG:       syslog_level = OS_LOG_TYPE_DEFAULT;     break;
188         case MDNS_LOG_OPERATION: syslog_level = OS_LOG_TYPE_INFO;        break;
189         case MDNS_LOG_SPS:       syslog_level = OS_LOG_TYPE_INFO;        break;
190         case MDNS_LOG_INFO:      syslog_level = OS_LOG_TYPE_INFO;        break;
191         case MDNS_LOG_DEBUG:     syslog_level = OS_LOG_TYPE_DEBUG;       break;
192         default:                 syslog_level = OS_LOG_TYPE_DEFAULT;     break;
193 #else
194         case MDNS_LOG_MSG:       syslog_level = LOG_ERR;     break;
195         case MDNS_LOG_OPERATION: syslog_level = LOG_WARNING; break;
196         case MDNS_LOG_SPS:       syslog_level = LOG_NOTICE;  break;
197         case MDNS_LOG_INFO:      syslog_level = LOG_INFO;    break;
198         case MDNS_LOG_DEBUG:     syslog_level = LOG_DEBUG;   break;
199         default:
200             fprintf(stderr, "Unknown loglevel %d, assuming LOG_ERR\n", loglevel);
201             fflush(stderr);
202 #endif
203         }
204 
205         if (!log_inited) { openlog(ident, LOG_CONS, LOG_DAEMON); log_inited++; }
206 
207 #if APPLE_OSX_mDNSResponder && LogTimeStamps
208         if (ident && ident[0] && mDNSPlatformClockDivisor)
209             syslog(syslog_level, "%8d.%03d: %s", (int)(t/1000), ms, buffer);
210         else
211 #endif
212         {
213 #if APPLE_OSX_mDNSResponder
214             mDNSPlatformLogToFile(syslog_level, buffer);
215 #else
216             syslog(syslog_level, "%s", buffer);
217 #endif
218         }
219     }
220 }
221