Compare commits

...

No commits in common. "master" and "philippe44_tsm" have entirely different histories.

25 changed files with 843 additions and 208 deletions

17
.gitattributes vendored Normal file
View File

@ -0,0 +1,17 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

60
.gitignore vendored
View File

@ -1,3 +1,57 @@
#syntax: glob
*.a
*.o
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# =========================
# Operating System Files
# =========================
# OSX
# =========================
.DS_Store
.AppleDouble
.LSOverride
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
__history/
Win32/
*.cb*
*.o
*.tds
*.res
*.map
*.il*
build

4
.hgignore Normal file
View File

@ -0,0 +1,4 @@
syntax: glob
*.a
*.o

View File

@ -1,38 +1,31 @@
#
# Makefile for tinysvcmdns
#
SRC = .
LIBRARY =
DEFINES = -DNDEBUG
CFLAGS += -Wall -pedantic -std=gnu99
#CFLAGS += -g
CFLAGS += -O2 -DNDEBUG
LDLIBS = -lpthread
vpath %.c $(SRC)
ifneq ($(CROSS_COMPILE),)
CC = gcc
CC := $(CROSS_COMPILE)$(CC)
AR := $(CROSS_COMPILE)$(AR)
endif
INCLUDE = -I$(SRC)
BIN=testmdnsd
SOURCES = mdns.c mdnsd.c tinysvcmdns.c
OBJECTS = $(patsubst %.c,$(OBJ)/%.o,$(SOURCES))
LIBTINYSVCMDNS_OBJS = mdns.o mdnsd.o
all: $(EXECUTABLE)
.PHONY: all clean
$(EXECUTABLE): $(OBJECTS)
$(CC) $(OBJECTS) $(LIBRARY) $(LDFLAGS) -o $@
all: $(BIN) libtinysvcmdns.a
$(OBJECTS): | bin $(OBJ)
$(OBJ):
@mkdir -p $@
bin:
@mkdir -p bin
$(OBJ)/%.o : %.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(INCLUDE) $< -c -o $@
clean:
-$(RM) *.o
-$(RM) *.bin
-$(RM) mdns
-$(RM) $(BIN)
-$(RM) libtinysvcmdns.a
mdns: mdns.o
mdnsd: mdns.o mdnsd.o
testmdnsd: testmdnsd.o libtinysvcmdns.a
libtinysvcmdns.a: $(patsubst %, libtinysvcmdns.a(%), $(LIBTINYSVCMDNS_OBJS))
rm -f $(OBJECTS) $(EXECUTABLE)

9
Makefile.arm Normal file
View File

@ -0,0 +1,9 @@
CC=armv5te-cross-linux-gnueabi-gcc
CFLAGS ?= -Wall -fPIC -O2 $(OPTS) $(INCLUDE) $(DEFINES)
LDFLAGS ?= -s -lpthread -lm -lrt -L.
OBJ = bin/arm
EXECUTABLE = bin/tinysvcmdns-arm
include Makefile

9
Makefile.bsd-x64 Normal file
View File

@ -0,0 +1,9 @@
CC = x86_64-cross-freebsd11-gcc
CFLAGS ?= -Wall -fPIC -ggdb -O2 $(OPTS) $(INCLUDE) $(DEFINES)
LDFLAGS ?= -s -lpthread -lcrypto -lm -lrt -lz -L.
OBJ = bin/bsd-x64
EXECUTABLE = bin/tinysvcmdns-bsd-x64
include Makefile

9
Makefile.i86pc-solaris Normal file
View File

@ -0,0 +1,9 @@
CC = i386-cross-solaris2.10-gcc
CFLAGS = -Wall -fPIC -O2 $(OPTS) $(INCLUDE) $(DEFINES)
LDFLAGS = -s -lpthread -ldl -lm -lrt -lsocket -lnsl -lz -L.
OBJ = bin/i86pc-solaris
EXECUTABLE = bin/tinysvcmdns-i86pc-solaris
include Makefile

9
Makefile.osx Normal file
View File

@ -0,0 +1,9 @@
CC = o64-gcc
CFLAGS ?= -Wall -fPIC -O2 $(OPTS) $(INCLUDE) $(DEFINES) -arch x86_64
LDFLAGS ?= -lpthread -ldl -lm -L. -arch x86_64 -mmacosx-version-min=10.10
OBJ = bin/osx
EXECUTABLE = bin/tinysvcmdns-osx
include Makefile

8
Makefile.x86 Normal file
View File

@ -0,0 +1,8 @@
CFLAGS ?= -Wall -fPIC -ggdb -O2 $(OPTS) $(INCLUDE) $(DEFINES)
LDFLAGS ?= -s -lpthread -lcrypto -ldl -lm -lrt -lz -L.
OBJ = bin/x86
EXECUTABLE = bin/tinysvcmdns-x86
include Makefile

View File

@ -1,13 +1,13 @@
NOTICE
=======
This is a fork from https://bitbucket.org/geekman/tinysvcmdns. It works under
Windows, OSX, and Linux (x86 and ARM) and with Embarcadero C++ builder XE7
which is not C11 compliant
This project is un-maintained, and has been since 2013.
I've added a function to stop a registered service, send bye-bye packet and
properly release all allocated memory
There are known vulnerabilities that have been disclosed, and quite possibly
others that have yet to be disclosed. Refer to the issue tracker.
You are advised to NOT use this library for any new projects / products.
I've also added a small real responder
----------------------------- original README -----------------------------
tinysvcmdns
============

57
README.txt Normal file
View File

@ -0,0 +1,57 @@
tinysvcmdns
============
tinysvcmdns is a tiny MDNS responder implementation for publishing services.
This implementation is only concerned with publishing services, without a
system-wide daemon like Bonjour or Avahi. Its other goal is to be extremely
small, embeddable, and have no external dependencies.
It only answers queries related to its own hostname (the A record), the
service PTRs, and the "_services.dns-sd._udp.local" name, which advertises
all services on a particular host.
Services consist of a single SRV and TXT record.
Decoding of MDNS packets is only done to retrieve the questions and answer RRs.
The purpose for decoding answer RRs is to make sure the service PTR is not
sent out if it is already included in the answer RRs.
It also only utilizes multicast packets, so no "QU" queries are accepted.
There is no name collision detection, so this means no queries are generated
before publishing the services. However compliant responders will avoid using
our names, since the implementation will respond to queries that match our
name.
TODO
-----
* better, more stable & complete API
* name collision detection
FILES
------
* mdns.c - provides data structures, parsing & encoding of MDNS packets
* mdnsd.c - implements the server socket, communication and thread
* testmdnsd.c - an example that creates an instance until terminated
LICENSE
--------
Copyright (C) 2011 Darell Tan
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

BIN
bin/cc32160mt.dll Normal file

Binary file not shown.

BIN
bin/pthreadBC2.dll Normal file

Binary file not shown.

BIN
bin/tinysvcmdns-arm Normal file

Binary file not shown.

BIN
bin/tinysvcmdns-bsd-x64 Normal file

Binary file not shown.

Binary file not shown.

BIN
bin/tinysvcmdns-osx Normal file

Binary file not shown.

BIN
bin/tinysvcmdns-x86 Normal file

Binary file not shown.

BIN
bin/tinysvcmdns.exe Normal file

Binary file not shown.

173
mdns.c
View File

@ -41,9 +41,6 @@
#endif
#define DEFAULT_TTL 120
struct name_comp {
uint8_t *label; // label
size_t pos; // position in msg
@ -54,10 +51,8 @@ struct name_comp {
// ----- label functions -----
// duplicates a name
inline uint8_t *dup_nlabel(const uint8_t *n) {
if (n == NULL)
return NULL;
//inline uint8_t *dup_nlabel(const uint8_t *n) {
uint8_t *dup_nlabel(const uint8_t *n) {
assert(n[0] <= 63); // prevent mis-use
return (uint8_t *) strdup((char *) n);
}
@ -65,9 +60,10 @@ inline uint8_t *dup_nlabel(const uint8_t *n) {
// duplicates a label
uint8_t *dup_label(const uint8_t *label) {
int len = *label + 1;
uint8_t *newlabel;
if (len > 63)
return NULL;
uint8_t *newlabel = malloc(len + 1);
newlabel = malloc(len + 1);
strncpy((char *) newlabel, (char *) label, len);
newlabel[len] = '\0';
return newlabel;
@ -93,33 +89,20 @@ uint8_t *join_nlabel(const uint8_t *n1, const uint8_t *n2) {
char *nlabel_to_str(const uint8_t *name) {
char *label, *labelp;
const uint8_t *p;
size_t buf_len = 256;
if (name == NULL)
return NULL;
assert(name != NULL);
label = labelp = malloc(buf_len);
label = labelp = malloc(256);
for (p = name; *p; p++) {
uint8_t label_len = *p;
if (buf_len <= label_len)
break;
strncpy(labelp, (char *) p + 1, label_len);
labelp += label_len;
strncpy(labelp, (char *) p + 1, *p);
labelp += *p;
*labelp = '.';
labelp++;
buf_len -= label_len + 1;
p += label_len;
p += *p;
}
// avoid writing NULL past end of buffer
if (buf_len == 0)
labelp--;
*labelp = '\0';
return label;
@ -153,9 +136,7 @@ uint8_t *create_label(const char *txt) {
int len;
uint8_t *s;
if (txt == NULL)
return NULL;
assert(txt != NULL);
len = strlen(txt);
if (len > 63)
return NULL;
@ -190,8 +171,9 @@ uint8_t *create_nlabel(const char *name) {
lenpos = p;
while (p < e) {
*lenpos = 0;
char *dot = memchr(p + 1, '.', e - p - 1);
*lenpos = 0;
if (dot == NULL)
dot = e + 1;
*lenpos = dot - p - 1;
@ -290,7 +272,7 @@ void rr_entry_destroy(struct rr_entry *rr) {
// check rr_type and free data elements
switch (rr->type) {
case RR_PTR:
if (rr->data.PTR.name)
if (rr->data.PTR.name)
free(rr->data.PTR.name);
// don't free entry
break;
@ -299,7 +281,7 @@ void rr_entry_destroy(struct rr_entry *rr) {
txt_rec = &rr->data.TXT;
while (txt_rec) {
struct rr_data_txt *next = txt_rec->next;
if (txt_rec->txt)
if (txt_rec->txt)
free(txt_rec->txt);
// only free() if it wasn't part of the struct
@ -315,6 +297,11 @@ void rr_entry_destroy(struct rr_entry *rr) {
free(rr->data.SRV.target);
break;
case RR_AAAA:
if (rr->data.AAAA.addr)
free(rr->data.AAAA.addr);
break;
default:
// nothing to free
break;
@ -342,6 +329,37 @@ int rr_list_count(struct rr_list *rr) {
return i;
}
struct rr_entry *rr_entry_remove(struct rr_group *group, struct rr_entry *entry, enum rr_type type) {
struct rr_group *g;
for (g = group; g; g = g->next) {
struct rr_list *lrr = g->rr, *prr= NULL;
for (; lrr; lrr = lrr->next) {
if (lrr->e->type == type) {
switch (type) {
case RR_PTR:
if (lrr->e->data.PTR.entry == entry) {
struct rr_entry *e = lrr->e;
if (prr == NULL) {
g->rr = lrr->next;
} else {
prr->next = lrr->next;
}
free(lrr);
return e;
}
break;
default:
break;
}
}
prr = lrr;
}
}
return NULL;
}
struct rr_entry *rr_list_remove(struct rr_list **rr_head, struct rr_entry *rr) {
struct rr_list *le = *rr_head, *pe = NULL;
for (; le; le = le->next) {
@ -361,6 +379,28 @@ struct rr_entry *rr_list_remove(struct rr_list **rr_head, struct rr_entry *rr) {
return NULL;
}
void rr_group_clean(struct rr_group **head) {
struct rr_group *le = *head, *pe = NULL;
while (le) {
if (le->rr == NULL) {
free(le->name);
if (pe == NULL) {
*head = le->next;
free(le);
le = *head;
} else {
pe->next = le->next;
free(le);
le = pe->next;
}
} else {
pe = le;
le = le->next;
}
}
}
// appends an rr_entry to an RR list
// if the RR is already in the list, it will not be added
// RRs are compared by memory location - not its contents
@ -395,10 +435,11 @@ int rr_list_append(struct rr_list **rr_head, struct rr_entry *rr) {
rr->cache_flush = 1; \
rr->rr_class = 1;
struct rr_entry *rr_create_a(uint8_t *name, uint32_t addr) {
struct rr_entry *rr_create_a(uint8_t *name, struct in_addr addr) {
DECL_MALLOC_ZERO_STRUCT(rr, rr_entry);
FILL_RR_ENTRY(rr, name, RR_A);
rr->data.A.addr = addr;
rr->data.A.addr = addr.s_addr;
rr->ttl = DEFAULT_TTL_FOR_RECORD_WITH_HOSTNAME; // 120 seconds -- see RFC 6762 Section 10
return rr;
}
@ -406,6 +447,7 @@ struct rr_entry *rr_create_aaaa(uint8_t *name, struct in6_addr *addr) {
DECL_MALLOC_ZERO_STRUCT(rr, rr_entry);
FILL_RR_ENTRY(rr, name, RR_AAAA);
rr->data.AAAA.addr = addr;
rr->ttl = DEFAULT_TTL_FOR_RECORD_WITH_HOSTNAME; // 120 seconds -- see RFC 6762 Section 10
return rr;
}
@ -414,6 +456,7 @@ struct rr_entry *rr_create_srv(uint8_t *name, uint16_t port, uint8_t *target) {
FILL_RR_ENTRY(rr, name, RR_SRV);
rr->data.SRV.port = port;
rr->data.SRV.target = target;
rr->ttl = DEFAULT_TTL_FOR_RECORD_WITH_HOSTNAME; // 120 seconds -- see RFC 6762 Section 10
return rr;
}
@ -422,6 +465,7 @@ struct rr_entry *rr_create_ptr(uint8_t *name, struct rr_entry *d_rr) {
FILL_RR_ENTRY(rr, name, RR_PTR);
rr->cache_flush = 0; // PTRs shouldn't have their cache flush bit set
rr->data.PTR.entry = d_rr;
rr->ttl = DEFAULT_TTL_FOR_RECORD_WITH_HOSTNAME; // 120 seconds -- see RFC 6762 Section 10
return rr;
}
@ -432,7 +476,7 @@ struct rr_entry *rr_create(uint8_t *name, enum rr_type type) {
}
void rr_set_nsec(struct rr_entry *rr_nsec, enum rr_type type) {
assert(rr_nsec->type = RR_NSEC);
assert(rr_nsec->type == RR_NSEC);
assert((type / 8) < sizeof(rr_nsec->data.NSEC.bitmap));
rr_nsec->data.NSEC.bitmap[ type / 8 ] = 1 << (7 - (type % 8));
@ -604,15 +648,9 @@ static size_t mdns_parse_qn(uint8_t *pkt_buf, size_t pkt_len, size_t off,
assert(pkt != NULL);
rr = malloc(sizeof(struct rr_entry));
if (rr == NULL)
goto err;
memset(rr, 0, sizeof(struct rr_entry));
name = uncompress_nlabel(pkt_buf, pkt_len, off);
if (name == NULL)
goto err;
p += label_len(pkt_buf, pkt_len, off);
rr->name = name;
@ -626,10 +664,6 @@ static size_t mdns_parse_qn(uint8_t *pkt_buf, size_t pkt_len, size_t off,
rr_list_append(&pkt->rr_qn, rr);
return p - (pkt_buf + off);
err:
free(rr);
return 0;
}
// parse the MDNS RR section
@ -650,15 +684,9 @@ static size_t mdns_parse_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off,
return 0;
rr = malloc(sizeof(struct rr_entry));
if (rr == NULL)
goto err;
memset(rr, 0, sizeof(struct rr_entry));
name = uncompress_nlabel(pkt_buf, pkt_len, off);
if (name == NULL)
goto err;
p += label_len(pkt_buf, pkt_len, off);
rr->name = name;
@ -677,7 +705,7 @@ static size_t mdns_parse_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off,
p += sizeof(uint16_t);
if (p + rr_data_len > e) {
DEBUG_PRINTF("rr_data_len goes beyond packet buffer: %lu > %lu\n", rr_data_len, e - p);
DEBUG_PRINTF("rr_data_len goes beyond packet buffer: %zu > %zu\n", rr_data_len, e - p);
rr_entry_destroy(rr);
return 0;
}
@ -688,7 +716,7 @@ static size_t mdns_parse_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off,
switch (rr->type) {
case RR_A:
if (rr_data_len < sizeof(uint32_t)) {
DEBUG_PRINTF("invalid rr_data_len=%lu for A record\n", rr_data_len);
DEBUG_PRINTF("invalid rr_data_len=%zu for A record\n", rr_data_len);
parse_error = 1;
break;
}
@ -696,17 +724,20 @@ static size_t mdns_parse_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off,
p += sizeof(uint32_t);
break;
case RR_AAAA:
case RR_AAAA: {
int i;
if (rr_data_len < sizeof(struct in6_addr)) {
DEBUG_PRINTF("invalid rr_data_len=%lu for AAAA record\n", rr_data_len);
DEBUG_PRINTF("invalid rr_data_len=%zu for AAAA record\n", rr_data_len);
parse_error = 1;
break;
}
rr->data.AAAA.addr = malloc(sizeof(struct in6_addr));
for (int i = 0; i < sizeof(struct in6_addr); i++)
for (i = 0; i < sizeof(struct in6_addr); i++)
rr->data.AAAA.addr->s6_addr[i] = p[i];
p += sizeof(struct in6_addr);
break;
}
case RR_PTR:
rr->data.PTR.name = uncompress_nlabel(pkt_buf, pkt_len, p - pkt_buf);
@ -737,7 +768,7 @@ static size_t mdns_parse_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off,
}
p += txt_rec->txt[0] + 1;
if (p >= e)
if (p >= e)
break;
// allocate another record
@ -761,10 +792,6 @@ static size_t mdns_parse_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off,
rr_list_append(&pkt->rr_ans, rr);
return p - (pkt_buf + off);
err:
free(rr);
return 0;
}
// parse a MDNS packet into an mdns_pkt struct
@ -820,7 +847,7 @@ struct mdns_pkt *mdns_parse_pkt(uint8_t *pkt_buf, size_t pkt_len) {
// encodes a name (label) into a packet using the name compression scheme
// encoded names will be added to the compression list for subsequent use
static size_t mdns_encode_name(uint8_t *pkt_buf, size_t pkt_len, size_t off,
static size_t mdns_encode_name(uint8_t *pkt_buf, size_t pkt_len, size_t off,
const uint8_t *name, struct name_comp *comp) {
struct name_comp *c, *c_tail = NULL;
uint8_t *p = pkt_buf + off;
@ -828,6 +855,10 @@ static size_t mdns_encode_name(uint8_t *pkt_buf, size_t pkt_len, size_t off,
if (name) {
while (*name) {
int segment_len;
// cache the name for subsequent compression
DECL_STRUCT(new_c, name_comp);
// find match for compression
for (c = comp; c; c = c->next) {
if (cmp_nlabel(name, c->label) == 0) {
@ -840,11 +871,9 @@ static size_t mdns_encode_name(uint8_t *pkt_buf, size_t pkt_len, size_t off,
}
// copy this segment
int segment_len = *name + 1;
segment_len = *name + 1;
strncpy((char *) p, (char *) name, segment_len);
// cache the name for subsequent compression
DECL_MALLOC_ZERO_STRUCT(new_c, name_comp);
MALLOC_ZERO_STRUCT(new_c, name_comp);
new_c->label = (uint8_t *) name;
new_c->pos = p - pkt_buf;
@ -967,6 +996,7 @@ size_t mdns_encode_pkt(struct mdns_pkt *answer, uint8_t *pkt_buf, size_t pkt_len
//uint8_t *e = pkt_buf + pkt_len;
size_t off;
int i;
struct rr_list *rr_set[3];
assert(answer != NULL);
assert(pkt_len >= 12);
@ -988,7 +1018,7 @@ size_t mdns_encode_pkt(struct mdns_pkt *answer, uint8_t *pkt_buf, size_t pkt_len
// allocate list for name compression
comp = malloc(sizeof(struct name_comp));
if (comp == NULL)
if (comp == NULL)
return -1;
memset(comp, 0, sizeof(struct name_comp));
@ -997,12 +1027,9 @@ size_t mdns_encode_pkt(struct mdns_pkt *answer, uint8_t *pkt_buf, size_t pkt_len
comp->pos = 0;
// skip encoding of qn
struct rr_list *rr_set[] = {
answer->rr_ans,
answer->rr_auth,
answer->rr_add
};
rr_set[0] = answer->rr_ans;
rr_set[1] = answer->rr_auth;
rr_set[2] = answer->rr_add;
// encode answer, authority and additional RRs
for (i = 0; i < sizeof(rr_set) / sizeof(rr_set[0]); i++) {

11
mdns.h
View File

@ -46,6 +46,12 @@
#define DECL_MALLOC_ZERO_STRUCT(x, type) \
struct type * MALLOC_ZERO_STRUCT(x, type)
#define DECL_STRUCT(x, type) \
struct type * x;
#define DEFAULT_TTL_FOR_RECORD_WITH_HOSTNAME 120
#define DEFAULT_TTL 4500
#ifndef NDEBUG
#define DEBUG_PRINTF(...) printf(__VA_ARGS__)
#else
@ -170,7 +176,10 @@ void rr_group_destroy(struct rr_group *group);
struct rr_group *rr_group_find(struct rr_group *g, uint8_t *name);
struct rr_entry *rr_entry_find(struct rr_list *rr_list, uint8_t *name, uint16_t type);
struct rr_entry *rr_entry_match(struct rr_list *rr_list, struct rr_entry *entry);
void rr_entry_destroy(struct rr_entry *rr);
struct rr_entry *rr_entry_remove(struct rr_group *group, struct rr_entry *entry, enum rr_type type);
void rr_group_add(struct rr_group **group, struct rr_entry *rr);
void rr_group_clean(struct rr_group **head);
int rr_list_count(struct rr_list *rr);
int rr_list_append(struct rr_list **rr_head, struct rr_entry *rr);
@ -180,7 +189,7 @@ void rr_list_destroy(struct rr_list *rr, char destroy_items);
struct rr_entry *rr_create_ptr(uint8_t *name, struct rr_entry *d_rr);
struct rr_entry *rr_create_srv(uint8_t *name, uint16_t port, uint8_t *target);
struct rr_entry *rr_create_aaaa(uint8_t *name, struct in6_addr *addr);
struct rr_entry *rr_create_a(uint8_t *name, uint32_t addr);
struct rr_entry *rr_create_a(uint8_t *name, struct in_addr addr);
struct rr_entry *rr_create(uint8_t *name, enum rr_type type);
void rr_set_nsec(struct rr_entry *rr_nsec, enum rr_type type);
void rr_add_txt(struct rr_entry *rr_txt, const char *txt);

214
mdnsd.c
View File

@ -48,7 +48,9 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <assert.h>
#include <pthread.h>
@ -80,6 +82,7 @@ struct mdnsd {
struct rr_group *group;
struct rr_list *announce;
struct rr_list *services;
struct rr_list *leave;
uint8_t *hostname;
};
@ -102,35 +105,58 @@ static void log_message(int loglevel, char *fmt_str, ...) {
fprintf(stderr, "%s\n", buf);
}
static int create_recv_sock() {
static int create_recv_sock(uint32_t host) {
int sd = socket(AF_INET, SOCK_DGRAM, 0);
int r = -1;
int on = 1;
char onChar = 1;
struct sockaddr_in serveraddr;
struct ip_mreq mreq;
socklen_t addrlen;
unsigned char ttl = 255;
if (sd < 0) {
log_message(LOG_ERR, "recv socket(): %m");
return sd;
}
int r = -1;
int on = 1;
if ((r = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on))) < 0) {
log_message(LOG_ERR, "recv setsockopt(SO_REUSEADDR): %m");
return r;
}
#if !defined(WIN32)
if (!getsockopt(sd, SOL_SOCKET, SO_REUSEPORT,(char*) &on, &addrlen)) {
on = 1;
if ((r = setsockopt(sd, SOL_SOCKET, SO_REUSEPORT,(char*) &on, sizeof(on))) < 0) {
log_message(LOG_ERR, "recv setsockopt(SO_REUSEPORT): %m", r);
}
}
#endif
/* bind to an address */
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(MDNS_PORT);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); /* receive multicast */
if ((r = bind(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0) {
log_message(LOG_ERR, "recv bind(): %m");
return r;
}
memset(&mreq, 0, sizeof(struct ip_mreq));
mreq.imr_interface.s_addr = host;
if ((r = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, (char*) &mreq.imr_interface.s_addr, sizeof(mreq.imr_interface.s_addr))) < 0) {
log_message(LOG_ERR, "recv setsockopt(IP_PROTO_IP): %m");
return r;
}
if ((r = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL, (void*) &ttl, sizeof(ttl))) < 0) {
log_message(LOG_ERR, "recv setsockopt(IP_MULTICAST_IP): %m");
return r;
}
// add membership to receiving socket
struct ip_mreq mreq;
memset(&mreq, 0, sizeof(struct ip_mreq));
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
mreq.imr_multiaddr.s_addr = inet_addr(MDNS_ADDR);
if ((r = setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq))) < 0) {
log_message(LOG_ERR, "recv setsockopt(IP_ADD_MEMBERSHIP): %m");
@ -138,13 +164,14 @@ static int create_recv_sock() {
}
// enable loopback in case someone else needs the data
if ((r = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, (char *) &on, sizeof(on))) < 0) {
if ((r = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, (char *) &onChar, sizeof(onChar))) < 0) {
log_message(LOG_ERR, "recv setsockopt(IP_MULTICAST_LOOP): %m");
return r;
}
#ifdef IP_PKTINFO
on = 1;
if ((r = setsockopt(sd, SOL_IP, IP_PKTINFO, (char *) &on, sizeof(on))) < 0) {
log_message(LOG_ERR, "recv setsockopt(IP_PKTINFO): %m");
return r;
@ -171,17 +198,19 @@ static ssize_t send_packet(int fd, const void *data, size_t len) {
// type can be RR_ANY, which populates all entries EXCEPT RR_NSEC
static int populate_answers(struct mdnsd *svr, struct rr_list **rr_head, uint8_t *name, enum rr_type type) {
int num_ans = 0;
struct rr_group *ans_grp;
struct rr_list *n;
// check if we have the records
pthread_mutex_lock(&svr->data_lock);
struct rr_group *ans_grp = rr_group_find(svr->group, name);
ans_grp = rr_group_find(svr->group, name);
if (ans_grp == NULL) {
pthread_mutex_unlock(&svr->data_lock);
return num_ans;
}
// decide which records should go into answers
struct rr_list *n = ans_grp->rr;
n = ans_grp->rr;
for (; n; n = n->next) {
// exclude NSEC for RR_ANY
if (type == RR_ANY && n->e->type == RR_NSEC)
@ -205,7 +234,7 @@ static void add_related_rr(struct mdnsd *svr, struct rr_list *list, struct mdns_
switch (ans->type) {
case RR_PTR:
// target host A, AAAA records
reply->num_add_rr += populate_answers(svr, &reply->rr_add,
reply->num_add_rr += populate_answers(svr, &reply->rr_add,
MDNS_RR_GET_PTR_NAME(ans), RR_ANY);
break;
@ -254,22 +283,24 @@ static void announce_srv(struct mdnsd *svr, struct mdns_pkt *reply, uint8_t *nam
// returns >0 if processed, 0 otherwise
static int process_mdns_pkt(struct mdnsd *svr, struct mdns_pkt *pkt, struct mdns_pkt *reply) {
int i;
struct rr_list *qnl;
struct rr_list *ans, *prev_ans;
assert(pkt != NULL);
// is it standard query?
if ((pkt->flags & MDNS_FLAG_RESP) == 0 &&
if ((pkt->flags & MDNS_FLAG_RESP) == 0 &&
MDNS_FLAG_GET_OPCODE(pkt->flags) == 0) {
mdns_init_reply(reply, pkt->id);
DEBUG_PRINTF("flags = %04x, qn = %d, ans = %d, add = %d\n",
DEBUG_PRINTF("flags = %04x, qn = %d, ans = %d, add = %d\n",
pkt->flags,
pkt->num_qn,
pkt->num_ans_rr,
pkt->num_add_rr);
// loop through questions
struct rr_list *qnl = pkt->rr_qn;
qnl = pkt->rr_qn;
for (i = 0; i < pkt->num_qn; i++, qnl = qnl->next) {
struct rr_entry *qn = qnl->e;
int num_ans_added = 0;
@ -291,7 +322,7 @@ static int process_mdns_pkt(struct mdnsd *svr, struct mdns_pkt *pkt, struct mdns
}
// remove our replies if they were already in their answers
struct rr_list *ans = NULL, *prev_ans = NULL;
ans = NULL; prev_ans = NULL;
for (ans = reply->rr_ans; ans; ) {
struct rr_list *next_ans = ans->next;
struct rr_entry *known_ans = rr_entry_match(pkt->rr_ans, ans->e);
@ -337,10 +368,13 @@ static int process_mdns_pkt(struct mdnsd *svr, struct mdns_pkt *pkt, struct mdns
int create_pipe(int handles[2]) {
#ifdef _WIN32
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr;
int len;
if (sock == INVALID_SOCKET) {
return -1;
}
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(0);
@ -353,7 +387,7 @@ int create_pipe(int handles[2]) {
closesocket(sock);
return -1;
}
int len = sizeof(serv_addr);
len = sizeof(serv_addr);
if (getsockname(sock, (SOCKADDR*)&serv_addr, &len) == SOCKET_ERROR) {
closesocket(sock);
return -1;
@ -413,13 +447,16 @@ static void main_loop(struct mdnsd *svr) {
fd_set sockfd_set;
int max_fd = svr->sockfd;
char notify_buf[2]; // buffer for reading of notify_pipe
struct mdns_pkt *mdns_reply;
struct mdns_pkt *mdns;
struct rr_list *svc_le;
void *pkt_buffer = malloc(PACKET_SIZE);
if (svr->notify_pipe[0] > max_fd)
max_fd = svr->notify_pipe[0];
struct mdns_pkt *mdns_reply = malloc(sizeof(struct mdns_pkt));
mdns_reply = malloc(sizeof(struct mdns_pkt));
memset(mdns_reply, 0, sizeof(struct mdns_pkt));
while (! svr->stop_flag) {
@ -435,14 +472,14 @@ static void main_loop(struct mdnsd *svr) {
struct sockaddr_in fromaddr;
socklen_t sockaddr_size = sizeof(struct sockaddr_in);
ssize_t recvsize = recvfrom(svr->sockfd, pkt_buffer, PACKET_SIZE, 0,
ssize_t recvsize = recvfrom(svr->sockfd, pkt_buffer, PACKET_SIZE, 0,
(struct sockaddr *) &fromaddr, &sockaddr_size);
if (recvsize < 0) {
log_message(LOG_ERR, "recv(): %m");
}
DEBUG_PRINTF("data from=%s size=%ld\n", inet_ntoa(fromaddr.sin_addr), (long) recvsize);
struct mdns_pkt *mdns = mdns_parse_pkt(pkt_buffer, recvsize);
mdns = mdns_parse_pkt(pkt_buffer, recvsize);
if (mdns != NULL) {
if (process_mdns_pkt(svr, mdns, mdns_reply)) {
size_t replylen = mdns_encode_pkt(mdns_reply, pkt_buffer, PACKET_SIZE);
@ -458,17 +495,18 @@ static void main_loop(struct mdnsd *svr) {
// send out announces
while (1) {
struct rr_entry *ann_e = NULL;
char *namestr;
// extract from head of list
pthread_mutex_lock(&svr->data_lock);
if (svr->announce)
if (svr->announce)
ann_e = rr_list_remove(&svr->announce, svr->announce->e);
pthread_mutex_unlock(&svr->data_lock);
if (! ann_e)
break;
char *namestr = nlabel_to_str(ann_e->name);
namestr = nlabel_to_str(ann_e->name);
DEBUG_PRINTF("sending announce for %s\n", namestr);
free(namestr);
@ -479,13 +517,45 @@ static void main_loop(struct mdnsd *svr) {
send_packet(svr->sockfd, pkt_buffer, replylen);
}
}
// send out bye-bye for terminating services
while (1) {
struct rr_entry *leave_e = NULL;
char *namestr;
pthread_mutex_lock(&svr->data_lock);
if (svr->leave)
leave_e = rr_list_remove(&svr->leave, svr->leave->e);
pthread_mutex_unlock(&svr->data_lock);
if (!leave_e)
break;
mdns_init_reply(mdns_reply, 0);
namestr = nlabel_to_str(leave_e->name);
DEBUG_PRINTF("sending bye-bye for %s\n", namestr);
free(namestr);
leave_e->ttl = 0;
mdns_reply->num_ans_rr += rr_list_append(&mdns_reply->rr_ans, leave_e);
// send out packet
if (mdns_reply->num_ans_rr > 0) {
size_t replylen = mdns_encode_pkt(mdns_reply, pkt_buffer, PACKET_SIZE);
send_packet(svr->sockfd, pkt_buffer, replylen);
}
rr_entry_destroy(leave_e->data.PTR.entry);
rr_entry_destroy(leave_e);
}
}
// main thread terminating. send out "goodbye packets" for services
mdns_init_reply(mdns_reply, 0);
pthread_mutex_lock(&svr->data_lock);
struct rr_list *svc_le = svr->services;
svc_le = svr->services;
for (; svc_le; svc_le = svc_le->next) {
// set TTL to zero
svc_le->e->ttl = 0;
@ -501,6 +571,7 @@ static void main_loop(struct mdnsd *svr) {
// destroy packet
mdns_init_reply(mdns_reply, 0);
free(mdns_reply);
free(pkt_buffer);
@ -513,7 +584,7 @@ static void main_loop(struct mdnsd *svr) {
/////////////////////////////////////////////////////
void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, uint32_t ip) {
void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, struct in_addr addr) {
struct rr_entry *a_e = NULL,
*nsec_e = NULL;
@ -521,9 +592,10 @@ void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, uint32_t ip) {
// dont ask me what happens if the IP changes
assert(svr->hostname == NULL);
a_e = rr_create_a(create_nlabel(hostname), ip);
a_e = rr_create_a(create_nlabel(hostname), addr);
nsec_e = rr_create(create_nlabel(hostname), RR_NSEC);
nsec_e->ttl = DEFAULT_TTL_FOR_RECORD_WITH_HOSTNAME;
rr_set_nsec(nsec_e, RR_A);
pthread_mutex_lock(&svr->data_lock);
@ -533,13 +605,33 @@ void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, uint32_t ip) {
pthread_mutex_unlock(&svr->data_lock);
}
void mdnsd_set_hostname_v6(struct mdnsd *svr, const char *hostname, struct in6_addr *addr) {
struct rr_entry *aaaa_e = NULL, *nsec_e = NULL;
// currently can't be called twice
// dont ask me what happens if the IP changes
assert(svr->hostname == NULL);
aaaa_e = rr_create_aaaa(create_nlabel(hostname), addr); // 120 seconds automatically
nsec_e = rr_create(create_nlabel(hostname), RR_NSEC);
nsec_e->ttl = DEFAULT_TTL_FOR_RECORD_WITH_HOSTNAME; // set to 120 seconds (default is 4500)
rr_set_nsec(nsec_e, RR_AAAA);
pthread_mutex_lock(&svr->data_lock);
svr->hostname = create_nlabel(hostname);
rr_group_add(&svr->group, aaaa_e);
rr_group_add(&svr->group, nsec_e);
pthread_mutex_unlock(&svr->data_lock);
}
void mdnsd_add_rr(struct mdnsd *svr, struct rr_entry *rr) {
pthread_mutex_lock(&svr->data_lock);
rr_group_add(&svr->group, rr);
pthread_mutex_unlock(&svr->data_lock);
}
struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_name,
struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_name,
const char *type, uint16_t port, const char *hostname, const char *txt[]) {
struct rr_entry *txt_e = NULL,
*srv_e = NULL,
@ -552,7 +644,7 @@ struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_
// combine service name
type_nlabel = create_nlabel(type);
inst_nlabel = create_nlabel(instance_name);
inst_nlabel = create_label(instance_name);
nlabel = join_nlabel(inst_nlabel, type_nlabel);
// create TXT record
@ -606,13 +698,60 @@ struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_
return service;
}
void mdns_service_remove(struct mdnsd *svr, struct mdns_service *svc) {
struct rr_list *rr;
assert(svr != NULL && svc != NULL);
// modify lists here
pthread_mutex_lock(&svr->data_lock);
for (rr = svc->entries; rr; rr = rr->next) {
struct rr_group *g;
struct rr_entry *ptr_e;
// remove entry from groups and destroy entries that are not PTR
if ((g = rr_group_find(svr->group, rr->e->name)) != NULL) {
rr_list_remove(&g->rr, rr->e);
}
// remove PTR and BPTR related to this SVC
if ((ptr_e = rr_entry_remove(svr->group, rr->e, RR_PTR)) != NULL) {
struct rr_entry *bptr_e;
// remove PTR from announce and services
rr_list_remove(&svr->announce, ptr_e);
rr_list_remove(&svr->services, ptr_e);
// find BPTR and remove it from groups
bptr_e = rr_entry_remove(svr->group, ptr_e, RR_PTR);
rr_entry_destroy(bptr_e);
// add PTR to list of announces for leaving
rr_list_append(&svr->leave, ptr_e);
} else {
// destroy entries not needed for sending "leave" packet
rr_entry_destroy(rr->e);
}
}
// remove all empty groups
rr_group_clean(&svr->group);
// destroy this service entries
rr_list_destroy(svc->entries, 0);
free(svc);
pthread_mutex_unlock(&svr->data_lock);
}
void mdns_service_destroy(struct mdns_service *srv) {
assert(srv != NULL);
rr_list_destroy(srv->entries, 0);
free(srv);
}
struct mdnsd *mdnsd_start() {
struct mdnsd *mdnsd_start(struct in_addr host) {
pthread_t tid;
pthread_attr_t attr;
@ -625,7 +764,7 @@ struct mdnsd *mdnsd_start() {
return NULL;
}
server->sockfd = create_recv_sock();
server->sockfd = create_recv_sock(host.s_addr);
if (server->sockfd < 0) {
log_message(LOG_ERR, "unable to create recv socket");
free(server);
@ -643,17 +782,19 @@ struct mdnsd *mdnsd_start() {
free(server);
return NULL;
}
return server;
}
void mdnsd_stop(struct mdnsd *s) {
assert(s != NULL);
struct timeval tv;
struct timeval tv = {
.tv_sec = 0,
.tv_usec = 500 * 1000,
};
if (!s) return;
tv.tv_sec = 0;
tv.tv_usec = 500*1000;
assert(s != NULL);
s->stop_flag = 1;
write_pipe(s->notify_pipe[1], ".", 1);
@ -668,6 +809,7 @@ void mdnsd_stop(struct mdnsd *s) {
rr_group_destroy(s->group);
rr_list_destroy(s->announce, 0);
rr_list_destroy(s->services, 0);
rr_list_destroy(s->leave, 0);
if (s->hostname)
free(s->hostname);

16
mdnsd.h
View File

@ -30,22 +30,25 @@
#define __MDNSD_H__
#include <stdint.h>
#ifdef _WIN32
#include <inaddr.h>
#else
#include <netinet/in.h>
#endif
struct mdnsd;
struct mdns_service;
// starts a MDNS responder instance
// returns NULL if unsuccessful
struct mdnsd *mdnsd_start();
struct mdnsd *mdnsd_start(struct in_addr host);
// stops the given MDNS responder instance
void mdnsd_stop(struct mdnsd *s);
// sets the hostname for the given MDNS responder instance
void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, uint32_t ip);
// adds an additional RR
void mdnsd_add_rr(struct mdnsd *svr, struct rr_entry *rr);
void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, struct in_addr addr);
// registers a service with the MDNS responder instance
struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_name,
@ -54,5 +57,8 @@ struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_
// destroys the mdns_service struct returned by mdnsd_register_svc()
void mdns_service_destroy(struct mdns_service *srv);
// remove AND destroys the mdns_service struct returned by mdnsd_register_svc()
void mdns_service_remove(struct mdnsd *svr, struct mdns_service *svc);
#endif/*!__MDNSD_H__*/

View File

@ -1,41 +1,24 @@
/*
* tinysvcmdns - a tiny MDNS implementation for publishing services
* Copyright (C) 2011 Darell Tan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef _WIN32
#include <winsock2.h>
#include <in6addr.h>
#include <ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#endif
#include <stdio.h>
#include "mdns.h"
#include "mdnsd.h"
@ -55,30 +38,6 @@ int main(int argc, char *argv[]) {
mdnsd_set_hostname(svr, hostname, inet_addr("192.168.0.29"));
struct rr_entry *a2_e = NULL;
a2_e = rr_create_a(create_nlabel(hostname), inet_addr("192.168.0.31"));
mdnsd_add_rr(svr, a2_e);
struct rr_entry *aaaa_e = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET6;
hints.ai_flags = AI_NUMERICHOST;
struct addrinfo* results;
getaddrinfo(
"fe80::e2f8:47ff:fe20:28e0",
NULL,
&hints,
&results);
struct sockaddr_in6* addr = (struct sockaddr_in6*)results->ai_addr;
struct in6_addr v6addr = addr->sin6_addr;
freeaddrinfo(results);
aaaa_e = rr_create_aaaa(create_nlabel(hostname), &v6addr);
mdnsd_add_rr(svr, aaaa_e);
const char *txt[] = {
"path=/mywebsite",
NULL

323
tinysvcmdns.c Normal file
View File

@ -0,0 +1,323 @@
/*
* tinysvcmdns - a tiny MDNS implementation for publishing services
* Copyright (C) 2011 Darell Tan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdbool.h>
#include <signal.h>
#include <stdint.h>
#ifdef _WIN32
#include <winsock2.h>
#include <in6addr.h>
#include <ws2tcpip.h>
typedef uint32_t in_addr_t;
#define strcasecmp stricmp
#elif defined (linux) || defined (__FreeBSD__) || defined (sun)
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <strings.h>
#if defined (__FreeBSD__) || defined (sun)
#include <ifaddrs.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#endif
#if defined (sun)
#include <sys/sockio.h>
#endif
#elif defined (__APPLE__)
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <ifaddrs.h>
#endif
#include "mdns.h"
#include "mdnsd.h"
struct mdns_service *svc;
struct mdnsd *svr;
/*---------------------------------------------------------------------------*/
#ifdef WIN32
static void winsock_init(void) {
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 2);
int WSerr = WSAStartup(wVersionRequested, &wsaData);
if (WSerr != 0) exit(1);
}
/*---------------------------------------------------------------------------*/
static void winsock_close(void) {
WSACleanup();
}
#endif
/*---------------------------------------------------------------------------*/
#define MAX_INTERFACES 256
#define DEFAULT_INTERFACE 1
#if !defined(WIN32)
#define INVALID_SOCKET (-1)
#endif
static in_addr_t get_localhost(char **name)
{
#ifdef WIN32
char buf[256];
struct hostent *h = NULL;
struct sockaddr_in LocalAddr;
memset(&LocalAddr, 0, sizeof(LocalAddr));
gethostname(buf, 256);
h = gethostbyname(buf);
if (name) *name = strdup(buf);
if (h != NULL) {
memcpy(&LocalAddr.sin_addr, h->h_addr_list[0], 4);
return LocalAddr.sin_addr.s_addr;
}
else return INADDR_ANY;
#elif defined (__APPLE__) || defined(__FreeBSD__)
struct ifaddrs *ifap, *ifa;
if (name) {
*name = malloc(256);
gethostname(*name, 256);
}
if (getifaddrs(&ifap) != 0) return INADDR_ANY;
/* cycle through available interfaces */
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
/* Skip loopback, point-to-point and down interfaces,
* except don't skip down interfaces
* if we're trying to get a list of configurable interfaces. */
if ((ifa->ifa_flags & IFF_LOOPBACK) ||
(!( ifa->ifa_flags & IFF_UP))) {
continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) {
/* We don't want the loopback interface. */
if (((struct sockaddr_in *)(ifa->ifa_addr))->sin_addr.s_addr ==
htonl(INADDR_LOOPBACK)) {
continue;
}
return ((struct sockaddr_in *)(ifa->ifa_addr))->sin_addr.s_addr;
break;
}
}
freeifaddrs(ifap);
return INADDR_ANY;
#else
char szBuffer[MAX_INTERFACES * sizeof (struct ifreq)];
struct ifconf ifConf;
struct ifreq ifReq;
int nResult;
long unsigned int i;
int LocalSock;
struct sockaddr_in LocalAddr;
int j = 0;
if (name) {
*name = malloc(256);
gethostname(*name, 256);
}
/* purify */
memset(&ifConf, 0, sizeof(ifConf));
memset(&ifReq, 0, sizeof(ifReq));
memset(szBuffer, 0, sizeof(szBuffer));
memset(&LocalAddr, 0, sizeof(LocalAddr));
/* Create an unbound datagram socket to do the SIOCGIFADDR ioctl on. */
LocalSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (LocalSock == INVALID_SOCKET) return false;
/* Get the interface configuration information... */
ifConf.ifc_len = (int)sizeof szBuffer;
ifConf.ifc_ifcu.ifcu_buf = (caddr_t) szBuffer;
nResult = ioctl(LocalSock, SIOCGIFCONF, &ifConf);
if (nResult < 0) {
close(LocalSock);
return INADDR_ANY;
}
/* Cycle through the list of interfaces looking for IP addresses. */
for (i = 0lu; i < (long unsigned int)ifConf.ifc_len && j < DEFAULT_INTERFACE; ) {
struct ifreq *pifReq =
(struct ifreq *)((caddr_t)ifConf.ifc_req + i);
i += sizeof *pifReq;
/* See if this is the sort of interface we want to deal with. */
memset(ifReq.ifr_name, 0, sizeof(ifReq.ifr_name));
strncpy(ifReq.ifr_name, pifReq->ifr_name,
sizeof(ifReq.ifr_name) - 1);
/* Skip loopback, point-to-point and down interfaces,
* except don't skip down interfaces
* if we're trying to get a list of configurable interfaces. */
ioctl(LocalSock, SIOCGIFFLAGS, &ifReq);
if ((ifReq.ifr_flags & IFF_LOOPBACK) ||
(!(ifReq.ifr_flags & IFF_UP))) {
continue;
}
if (pifReq->ifr_addr.sa_family == AF_INET) {
/* Get a pointer to the address...*/
memcpy(&LocalAddr, &pifReq->ifr_addr,
sizeof pifReq->ifr_addr);
/* We don't want the loopback interface. */
if (LocalAddr.sin_addr.s_addr ==
htonl(INADDR_LOOPBACK)) {
continue;
}
}
/* increment j if we found an address which is not loopback
* and is up */
j++;
}
close(LocalSock);
return LocalAddr.sin_addr.s_addr;
#endif
}
/*---------------------------------------------------------------------------*/
static int print_usage(void) {
printf("[host <ip>] <identity> <type> <port> <txt> [txt] ... [txt]\n");
#ifdef WIN32
winsock_close();
#endif
return 1;
}
/*---------------------------------------------------------------------------*/
static void sighandler(int signum) {
mdnsd_stop(svr);
#ifdef WIN32
winsock_close();
#endif
exit(0);
}
/*---------------------------------------------------------------------------*/
/* */
/*---------------------------------------------------------------------------*/
#ifdef MDNS_SVC
int mdns_server(int argc, char *argv[]) {
#else
int main(int argc, char *argv[]) {
#endif
char type[255];
int port;
const char **txt;
struct in_addr host;
char *hostname;
int opt = 0;
signal(SIGINT, sighandler);
signal(SIGTERM, sighandler);
#if defined(SIGPIPE)
signal(SIGPIPE, SIG_IGN);
#endif
#if defined(SIGQUIT)
signal(SIGQUIT, sighandler);
#endif
#if defined(SIGHUP)
signal(SIGHUP, sighandler);
#endif
#ifdef WIN32
winsock_init();
#endif
host.s_addr = get_localhost(&hostname);
hostname = realloc(hostname, strlen(hostname) + strlen(".local") + 1);
strcat(hostname, ".local");
if (!strcasecmp(argv[1], "host")) {
host.s_addr = inet_addr(argv[2]);
opt = 2;
}
if (host.s_addr == INADDR_ANY) {
printf("cannot find host address\n");
free(hostname);
return print_usage();
}
if (argc < 5+opt) return print_usage();
port = atoi(argv[3+opt]);
svr = mdnsd_start(host);
if (svr == NULL) return print_usage();
txt = malloc((argc - 4 + 1 - opt) * sizeof(char**));
memcpy(txt, argv + 4 + opt, (argc - 4 - opt) * sizeof(char**));
txt[argc - 4 - opt] = NULL;
mdnsd_set_hostname(svr, hostname, host);
sprintf(type, "%s.local", argv[2 + opt]);
printf("host : %s\nidentity : %s\ntype : %s\n"
"ip : %s\nport : %u\n",
hostname, argv[1 + opt], type, inet_ntoa(host), port);
free(hostname);
svc = mdnsd_register_svc(svr, argv[1 + opt], type, port, NULL, txt);
// or, to remove service call: mdns_service_remove(svr, svc);
mdns_service_destroy(svc);
#ifdef WIN32
Sleep(INFINITE);
#else
pause();
#endif
mdnsd_stop(svr);
#ifdef WIN32
winsock_close();
#endif
return 0;
}