dns-sd.c revision 4b22b9337f359bfd063322244f5336cc7c6ffcfa
/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2002-2006 Apple Computer, Inc. All rights reserved.
*
* Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
* ("Apple") in consideration of your agreement to the following terms, and your
* use, installation, modification or redistribution of this Apple software
* constitutes acceptance of these terms. If you do not agree with these terms,
* please do not use, install, modify or redistribute this Apple software.
*
* In consideration of your agreement to abide by the following terms, and subject
* to these terms, Apple grants you a personal, non-exclusive license, under Apple's
* copyrights in this original Apple software (the "Apple Software"), to use,
* reproduce, modify and redistribute the Apple Software, with or without
* the Apple Software in its entirety and without modifications, you must retain
* this notice and the following text and disclaimers in all such redistributions of
* the Apple Software. Neither the name, trademarks, service marks or logos of
* Apple Computer, Inc. may be used to endorse or promote products derived from the
* Apple Software without specific prior written permission from Apple. Except as
* expressly stated in this notice, no other rights or licenses, express or implied,
* are granted by Apple herein, including but not limited to any patent rights that
* may be infringed by your derivative works or by other works in which the Apple
* Software may be incorporated.
*
* The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
* COMBINATION WITH YOUR PRODUCTS.
*
* IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Formatting notes:
* This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
* on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
* but for the sake of brevity here I will say just this: Curly braces are not syntactially
* part of an "if" statement; they are the beginning and ending markers of a compound statement;
* therefore common sense dictates that if they are part of a compound statement then they
* should be indented to the same level as everything else in that compound statement.
* Indenting curly braces at the same level as the "if" implies that curly braces are
* part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
* thinking that variables x and y are both of type "char*" -- and anyone who doesn't
* understand why variable y is not of type "char*" just proves the point that poor code
* layout leads people to unfortunate misunderstandings about how the C language really works.)
To build this tool, copy and paste the following into a command line:
OS X:
gcc dns-sd.c -o dns-sd
POSIX systems:
gcc dns-sd.c -o dns-sd -I../mDNSShared -ldns_sd
Windows:
cl dns-sd.c -I../mDNSShared -DNOT_HAVE_GETOPT ws2_32.lib ..\mDNSWindows\DLL\Release\dnssd.lib
(may require that you run a Visual Studio script such as vsvars32.bat first)
*/
#pragma ident "%Z%%M% %I% %E% SMI"
// For testing changes to dnssd_clientstub.c, uncomment this line and the #include below
// #define __APPLE_API_PRIVATE 1
#include "dns_sd.h"
#include <ctype.h>
#include <stdio.h> // For stdout, stderr
#include <stdlib.h> // For exit()
#include <string.h> // For strlen(), strcpy(), bzero()
#include <errno.h> // For errno, EINTR
#include <time.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <process.h>
typedef int pid_t;
#define strcasecmp _stricmp
static const char kFilePathSep = '\\';
#else
#include <unistd.h> // For getopt() and optind
#include <netdb.h> // For getaddrinfo()
static const char kFilePathSep = '/';
#endif
//#include "../mDNSShared/dnssd_clientstub.c"
//*************************************************************************************************************
// Globals
static int operation;
static int num_printed;
static char addtest = 0;
static char bigNULL[8200];
// Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
#define LONG_TIME 100000000
static volatile int stopNow = 0;
//*************************************************************************************************************
// Supporting Utility Function
{
else return(atoi(s));
}
//*************************************************************************************************************
// Sample callback functions for each of the operation types
static void printtimestamp(void)
{
int ms;
#ifdef _WIN32
#else
#endif
}
{
{
char c = *cstr++;
if (c == '\\')
{
c = *cstr++;
{
}
}
*ptr++ = c;
}
*ptr++ = 0;
return(cstr);
}
static void DNSSD_API enum_reply(DNSServiceRef client, const DNSServiceFlags flags, uint32_t ifIndex,
{
DNSServiceFlags partialflags = flags & ~(kDNSServiceFlagsMoreComing | kDNSServiceFlagsAdd | kDNSServiceFlagsDefault);
char text[64];
const char *label[128];
(void)client; // Unused
(void)ifIndex; // Unused
(void)context; // Unused
// 1. Print the header
if (num_printed++ == 0) printf("Timestamp Recommended %s domain\n", operation == 'E' ? "Registration" : "Browsing");
if (errorCode)
else if (!*replyDomain)
printf("Error: No reply domain\n");
else
{
else printf(" ");
// 2. Count the labels
while (*replyDomain)
{
}
// 3. Decide if we're going to clump the last two or three labels (e.g. "apple.com", or "nicta.com.au")
if (labels >= 3 && replyDomain - label[labels-1] <= 3 && label[labels-1] - label[labels-2] <= 4) initial = 3;
else initial = 1;
// 4. Print the initial one-, two- or three-label clump
for (i=0; i<initial; i++)
{
if (i>0) printf(".");
}
printf("\n");
// 5. Print the remainder of the hierarchy
{
printf(" ");
}
}
}
static void DNSSD_API browse_reply(DNSServiceRef client, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
{
(void)client; // Unused
(void)context; // Unused
if (num_printed++ == 0) printf("Timestamp A/R Flags if %-25s %-25s %s\n", "Domain", "Service Type", "Instance Name");
}
{
{
{
// We'd like the output to be shell-friendly, so that it can be copied and pasted unchanged into a "dns-sd -R" command.
// However, this is trickier than it seems. Enclosing a string in double quotes doesn't necessarily make it
// shell-safe, because shells still expand variables like $foo even when they appear inside quoted strings.
// Enclosing a string in single quotes is better, but when using single quotes even backslash escapes are ignored,
// meaning there's simply no way to represent a single quote (or apostrophe) inside a single-quoted string.
// The only remaining solution is not to surround the string with quotes at all, but instead to use backslash
// escapes to encode spaces and all other known shell metacharacters.
// (If we've missed any known shell metacharacters, please let us know.)
// In addition, non-printing ascii codes (0-31) are displayed as \xHH, using a two-digit hex value.
// Because '\' is itself a shell metacharacter (the shell escape character), it has to be escaped as "\\" to survive
// the round-trip to the shell and back. This means that a single '\' is represented here as EIGHT backslashes:
// The C compiler eats half of them, resulting in four appearing in the output.
// The shell parses those four as a pair of "\\" sequences, passing two backslashes to the "dns-sd -R" command.
// The "dns-sd -R" command interprets this single "\\" pair as an escaped literal backslash. Sigh.
ptr++;
}
}
}
static void DNSSD_API resolve_reply(DNSServiceRef client, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txtRecord, void *context)
{
(void)client; // Unused
(void)ifIndex; // Unused
(void)context; // Unused
else
{
// Don't show degenerate TXT records containing nothing but a single empty string
printf("\n");
}
}
static void myTimerCallBack(void)
{
switch (operation)
{
case 'A':
{
switch (addtest)
{
case 0: printf("Adding Test HINFO record\n");
err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_HINFO, sizeof(myhinfoW), &myhinfoW[0], 0);
addtest = 1;
break;
addtest = 2;
break;
addtest = 0;
break;
}
}
break;
case 'U':
{
}
break;
case 'N':
{
printf("Adding big NULL record\n");
err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_NULL, sizeof(bigNULL), &bigNULL[0], 0);
}
break;
}
if (err != kDNSServiceErr_NoError)
{
stopNow = 1;
}
}
static void DNSSD_API reg_reply(DNSServiceRef client, const DNSServiceFlags flags, DNSServiceErrorType errorCode,
{
(void)client; // Unused
(void)flags; // Unused
(void)context; // Unused
if (errorCode == kDNSServiceErr_NoError)
{
printf("Name now registered and active\n");
}
else if (errorCode == kDNSServiceErr_NameConflict)
{
printf("Name in use, please choose another\n");
exit(-1);
}
else
}
static void DNSSD_API qr_reply(DNSServiceRef sdRef, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
const char *fullname, uint16_t rrtype, uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context)
{
char rdb[1000];
int unknowntype = 0;
(void)sdRef; // Unused
(void)flags; // Unused
(void)ifIndex; // Unused
(void)ttl; // Unused
(void)context; // Unused
if (errorCode)
else
{
switch (rrtype)
{
case kDNSServiceType_AAAA: sprintf(rdb, "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
break;
}
printf("\n");
if (operation == 'C')
if (flags & kDNSServiceFlagsAdd)
}
}
//*************************************************************************************************************
// The main test function
static void HandleEvents(void)
{
int result;
while (!stopNow)
{
// 1. Set up the fd_set as usual here.
// This example client has no file descriptors of its own,
// but a real application would call FD_SET to add them to the set here
// 2. Add the fd for our client(s) to the fd_set
// 3. Set up the timeout.
if (result > 0)
{
}
else if (result == 0)
else
{
}
}
}
// Return the recognized option in optstr and the option index of the next arg.
#if NOT_HAVE_GETOPT
{
int i;
for ( i=1; i < argc; i++)
{
{
*pOptInd = i + 1;
return argv[i][1];
}
}
return -1;
}
#else
{
return operation;
}
#endif
static void DNSSD_API MyRegisterRecordCallback(DNSServiceRef service, DNSRecordRef record, const DNSServiceFlags flags,
{
(void)service; // Unused
(void)record; // Unused
(void)flags; // Unused
switch (errorCode)
{
}
}
{
unsigned long ip = 0;
{
}
if (addrs)
{
}
return(ip);
}
static DNSServiceErrorType RegisterProxyAddressRecord(DNSServiceRef *sdRef, const char *host, const char *ip)
{
// Call getip() after the call DNSServiceCreateConnection().
// On the Win32 platform, WinSock must be initialized for getip() to succeed.
// Any DNSService* call will initialize WinSock for us, so we make sure
// DNSServiceCreateConnection() is called before getip() is.
unsigned long addr = 0;
return(DNSServiceRegisterRecord(*sdRef, &record, kDNSServiceFlagsUnique, kDNSServiceInterfaceIndexAny, host,
kDNSServiceType_A, kDNSServiceClass_IN, sizeof(addr), &addr, 240, MyRegisterRecordCallback, (void*)host));
// Note, should probably add support for creating proxy AAAA records too, one day
}
((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : 0)
const char *nam, const char *typ, const char *dom, const char *host, const char *port, int argc, char **argv)
{
int i;
if (nam[0] == '.' && nam[1] == 0) nam = ""; // We allow '.' on the command line as a synonym for empty string
if (dom[0] == '.' && dom[1] == 0) dom = ""; // We allow '.' on the command line as a synonym for empty string
if (argc)
{
for (i = 0; i < argc; i++)
{
const char *p = argv[i];
*ptr = 0;
{
}
}
printf("\n");
}
return(DNSServiceRegister(sdRef, /* kDNSServiceFlagsAllowRemoteQuery */ 0, opinterface, nam, typ, dom, host, registerPort.NotAnInteger, (uint16_t) (ptr-txt), txt, reg_reply, NULL));
}
{
char *dom;
int optind;
// Extract the program name from argv[0], which by convention contains the path to this executable.
// Note that this is just a voluntary convention, not enforced by the kernel --
// the process calling exec() can pass bogus data in argv[0] if it chooses to.
{
argc--;
argv++;
printf("Using LocalOnly\n");
}
{
argc -= 2;
argv += 2;
}
switch (operation)
{
err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsRegistrationDomains, opinterface, enum_reply, NULL);
break;
err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsBrowseDomains, opinterface, enum_reply, NULL);
//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "nicta.com.au.", NULL);
//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "bonjour.nicta.com.au.", NULL);
//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "ibm.com.", NULL);
//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "dns-sd.ibm.com.", NULL);
break;
if (dom[0] == '.' && dom[1] == 0) dom[0] = 0; // We allow '.' on the command line as a synonym for empty string
break;
if (dom[0] == '.' && dom[1] == 0) dom = "local"; // We allow '.' on the command line as a synonym for "local"
err = DNSServiceResolve(&client, 0, opinterface, argv[optind+0], argv[optind+1], dom, (DNSServiceResolveReply)resolve_reply, NULL);
break;
err = RegisterService(&client, argv[optind+0], argv[optind+1], argv[optind+2], NULL, argv[optind+3], argc-(optind+4), argv+(optind+4));
break;
if (err) break;
err = RegisterService(&client, argv[optind+0], argv[optind+1], argv[optind+2], argv[optind+4], argv[optind+3], argc-(optind+6), argv+(optind+6));
break;
case 'Q':
case 'C': {
if (rrtype == kDNSServiceType_TXT || rrtype == kDNSServiceType_PTR) flags |= kDNSServiceFlagsLongLivedQuery;
err = DNSServiceQueryRecord(&client, flags, opinterface, argv[optind+0], rrtype, rrclass, qr_reply, NULL);
break;
}
case 'A':
case 'U':
case 'N': {
static const char TXT[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
printf("Registering Service Test._testupdate._tcp.local.\n");
err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testupdate._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT)-1, TXT, reg_reply, NULL);
break;
}
case 'T': {
char TXT[1024];
unsigned int i;
for (i=0; i<sizeof(TXT); i++)
printf("Registering Service Test._testlargetxt._tcp.local.\n");
err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testlargetxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT), TXT, reg_reply, NULL);
break;
}
case 'M': {
static const char TXT1[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
static const char TXT2[] = "\xD" "Fourth String" "\xC" "Fifth String" "\xC" "Sixth String";
printf("Registering Service Test._testdualtxt._tcp.local.\n");
err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testdualtxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT1)-1, TXT1, reg_reply, NULL);
if (!err) err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_TXT, sizeof(TXT2)-1, TXT2, 0);
break;
}
case 'I': {
static const char TXT[] = "\x09" "Test Data";
printf("Registering Service Test._testtxt._tcp.local.\n");
err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testtxt._tcp.", "", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
break;
}
default: goto Fail;
}
if (!client || err != kDNSServiceErr_NoError) { fprintf(stderr, "DNSService call failed %ld\n", (long int)err); return (-1); }
HandleEvents();
// Be sure to deallocate the DNSServiceRef when you're finished
return 0;
Fail:
return 0;
}