getdns-1.5.1/0000755000175000017500000000000013416117763010014 500000000000000getdns-1.5.1/spec/0000755000175000017500000000000013416117763010746 500000000000000getdns-1.5.1/spec/example/0000755000175000017500000000000013416117763012401 500000000000000getdns-1.5.1/spec/example/example-tree.c0000644000175000017500000000762213416117763015064 00000000000000#include #include #include #include /* Set up the callback function, which will also do the processing of the results */ void callback(getdns_context *context, getdns_callback_type_t callback_type, getdns_dict *response, void *userarg, getdns_transaction_t transaction_id) { getdns_return_t r; /* Holder for all function returns */ getdns_list *replies_tree; size_t n_replies, i; (void) context; (void) userarg; /* unused parameters */ switch(callback_type) { case GETDNS_CALLBACK_CANCEL: printf("Transaction with ID %"PRIu64" was cancelled.\n", transaction_id); return; case GETDNS_CALLBACK_TIMEOUT: printf("Transaction with ID %"PRIu64" timed out.\n", transaction_id); return; case GETDNS_CALLBACK_ERROR: printf("An error occurred for transaction ID %"PRIu64".\n", transaction_id); return; default: break; } assert( callback_type == GETDNS_CALLBACK_COMPLETE ); if ((r = getdns_dict_get_list(response, "replies_tree", &replies_tree))) fprintf(stderr, "Could not get \"replies_tree\" from response"); else if ((r = getdns_list_get_length(replies_tree, &n_replies))) fprintf(stderr, "Could not get replies_tree\'s length"); else for (i = 0; i < n_replies && r == GETDNS_RETURN_GOOD; i++) { getdns_dict *reply; getdns_list *answer; size_t n_answers, j; if ((r = getdns_list_get_dict(replies_tree, i, &reply))) fprintf(stderr, "Could not get address %zu from just_address_answers", i); else if ((r = getdns_dict_get_list(reply, "answer", &answer))) fprintf(stderr, "Could not get \"address_data\" from address"); else if ((r = getdns_list_get_length(answer, &n_answers))) fprintf(stderr, "Could not get answer section\'s length"); else for (j = 0; j < n_answers && r == GETDNS_RETURN_GOOD; j++) { getdns_dict *rr; getdns_bindata *address = NULL; if ((r = getdns_list_get_dict(answer, j, &rr))) fprintf(stderr, "Could net get rr %zu from answer section", j); else if (getdns_dict_get_bindata(rr, "/rdata/ipv4_address", &address) == GETDNS_RETURN_GOOD) printf("The IPv4 address is "); else if (getdns_dict_get_bindata(rr, "/rdata/ipv6_address", &address) == GETDNS_RETURN_GOOD) printf("The IPv6 address is "); if (address) { char *address_str; if (!(address_str = getdns_display_ip_address(address))) { fprintf(stderr, "Could not convert second address to string"); r = GETDNS_RETURN_MEMORY_ERROR; break; } printf("%s\n", address_str); free(address_str); } } } if (r) { assert( r != GETDNS_RETURN_GOOD ); fprintf(stderr, ": %d\n", r); } getdns_dict_destroy(response); } int main() { getdns_return_t r; /* Holder for all function returns */ getdns_context *context = NULL; struct event_base *event_base = NULL; getdns_dict *extensions = NULL; char *query_name = "www.example.com"; /* Could add things here to help identify this call */ char *userarg = NULL; getdns_transaction_t transaction_id; if ((r = getdns_context_create(&context, 1))) fprintf(stderr, "Trying to create the context failed"); else if (!(event_base = event_base_new())) fprintf(stderr, "Trying to create the event base failed.\n"); else if ((r = getdns_extension_set_libevent_base(context, event_base))) fprintf(stderr, "Setting the event base failed"); else if ((r = getdns_address( context, query_name, extensions , userarg, &transaction_id, callback))) fprintf(stderr, "Error scheduling asynchronous request"); else if (event_base_dispatch(event_base) < 0) fprintf(stderr, "Error dispatching events\n"); /* Clean up */ if (event_base) event_base_free(event_base); if (context) getdns_context_destroy(context); /* Assuming we get here, leave gracefully */ exit(EXIT_SUCCESS); } getdns-1.5.1/spec/example/example-synchronous.c0000644000175000017500000000371313416117763016514 00000000000000#include #include #include int main() { getdns_return_t r; /* Holder for all function returns */ getdns_context *context = NULL; getdns_dict *response = NULL; getdns_dict *extensions = NULL; getdns_bindata *address_data; char *first = NULL, *second = NULL; /* Create the DNS context for this call */ if ((r = getdns_context_create(&context, 1))) fprintf(stderr, "Trying to create the context failed"); else if (!(extensions = getdns_dict_create())) fprintf(stderr, "Could not create extensions dict.\n"); else if ((r = getdns_dict_set_int(extensions, "return_both_v4_and_v6", GETDNS_EXTENSION_TRUE))) fprintf(stderr, "Trying to set an extension do both IPv4 and IPv6 failed"); else if ((r = getdns_general_sync(context, "example.com", GETDNS_RRTYPE_A, extensions, &response))) fprintf(stderr, "Error scheduling synchronous request"); else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/0/address_data", &address_data))) fprintf(stderr, "Could not get first address"); else if (!(first = getdns_display_ip_address(address_data))) fprintf(stderr, "Could not convert first address to string\n"); else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/1/address_data", &address_data))) fprintf(stderr, "Could not get second address"); else if (!(second = getdns_display_ip_address(address_data))) fprintf(stderr, "Could not convert second address to string\n"); if (first) { printf("The address is %s\n", first); free(first); } if (second) { printf("The address is %s\n", second); free(second); } /* Clean up */ if (response) getdns_dict_destroy(response); if (extensions) getdns_dict_destroy(extensions); if (context) getdns_context_destroy(context); if (r) { assert( r != GETDNS_RETURN_GOOD ); fprintf(stderr, ": %d\n", r); exit(EXIT_FAILURE); } /* Assuming we get here, leave gracefully */ exit(EXIT_SUCCESS); } getdns-1.5.1/spec/example/getdns_libevent.h0000644000175000017500000000362713416117763015656 00000000000000/* * Copyright (c) 2013, NLNet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 "config.h" #include #include #ifdef HAVE_EVENT2_EVENT_H #include #else #include #endif #ifndef HAVE_EVENT_BASE_FREE #define event_base_free(x) /* nop */ #endif #ifndef HAVE_EVENT_BASE_NEW #define event_base_new event_init #endif #ifndef HAVE_U_CHAR typedef unsigned char u_char; #endif getdns-1.5.1/spec/example/getdns_core_only.h0000644000175000017500000000306113416117763016027 00000000000000/* * Copyright (c) 2013, NLNet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 getdns-1.5.1/spec/example/example-simple-answers.c0000644000175000017500000000700213416117763017066 00000000000000#include #include #include #include /* Set up the callback function, which will also do the processing of the results */ void callback(getdns_context *context, getdns_callback_type_t callback_type, getdns_dict *response, void *userarg, getdns_transaction_t transaction_id) { getdns_return_t r; /* Holder for all function returns */ uint32_t status; getdns_bindata *address_data; char *first = NULL, *second = NULL; (void) context; /* unused parameter */ printf( "Callback for query \"%s\" with request ID %"PRIu64".\n" , (char *)userarg, transaction_id ); switch(callback_type) { case GETDNS_CALLBACK_CANCEL: printf("Transaction with ID %"PRIu64" was cancelled.\n", transaction_id); return; case GETDNS_CALLBACK_TIMEOUT: printf("Transaction with ID %"PRIu64" timed out.\n", transaction_id); return; case GETDNS_CALLBACK_ERROR: printf("An error occurred for transaction ID %"PRIu64".\n", transaction_id); return; default: break; } assert( callback_type == GETDNS_CALLBACK_COMPLETE ); if ((r = getdns_dict_get_int(response, "status", &status))) fprintf(stderr, "Could not get \"status\" from response"); else if (status != GETDNS_RESPSTATUS_GOOD) fprintf(stderr, "The search had no results, and a return value of %"PRIu32".\n", status); else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/0/address_data", &address_data))) fprintf(stderr, "Could not get first address"); else if (!(first = getdns_display_ip_address(address_data))) fprintf(stderr, "Could not convert first address to string\n"); else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/1/address_data", &address_data))) fprintf(stderr, "Could not get second address"); else if (!(second = getdns_display_ip_address(address_data))) fprintf(stderr, "Could not convert second address to string\n"); if (first) { printf("The address is %s\n", first); free(first); } if (second) { printf("The address is %s\n", second); free(second); } if (r) { assert( r != GETDNS_RETURN_GOOD ); fprintf(stderr, ": %d\n", r); } getdns_dict_destroy(response); } int main() { getdns_return_t r; /* Holder for all function returns */ getdns_context *context = NULL; struct event_base *event_base = NULL; getdns_dict *extensions = NULL; char *query_name = "www.example.com"; /* Could add things here to help identify this call */ char *userarg = query_name; getdns_transaction_t transaction_id; if ((r = getdns_context_create(&context, 1))) fprintf(stderr, "Trying to create the context failed"); else if (!(event_base = event_base_new())) fprintf(stderr, "Trying to create the event base failed.\n"); else if ((r = getdns_extension_set_libevent_base(context, event_base))) fprintf(stderr, "Setting the event base failed"); else if ((r = getdns_address( context, query_name, extensions , userarg, &transaction_id, callback))) fprintf(stderr, "Error scheduling asynchronous request"); else { printf("Request with transaction ID %"PRIu64" scheduled.\n", transaction_id); if (event_base_dispatch(event_base) < 0) fprintf(stderr, "Error dispatching events\n"); } /* Clean up */ if (event_base) event_base_free(event_base); if (context) getdns_context_destroy(context); /* Assuming we get here, leave gracefully */ exit(EXIT_SUCCESS); } getdns-1.5.1/spec/example/example-reverse.c0000644000175000017500000000725013416117763015575 00000000000000#include #include #include #include /* Set up the callback function, which will also do the processing of the results */ void callback(getdns_context *context, getdns_callback_type_t callback_type, getdns_dict *response, void *userarg, getdns_transaction_t transaction_id) { getdns_return_t r; /* Holder for all function returns */ getdns_list *answer; size_t n_answers, i; (void) context; (void) userarg; /* unused parameters */ switch(callback_type) { case GETDNS_CALLBACK_CANCEL: printf("Transaction with ID %"PRIu64" was cancelled.\n", transaction_id); return; case GETDNS_CALLBACK_TIMEOUT: printf("Transaction with ID %"PRIu64" timed out.\n", transaction_id); return; case GETDNS_CALLBACK_ERROR: printf("An error occurred for transaction ID %"PRIu64".\n", transaction_id); return; default: break; } assert( callback_type == GETDNS_CALLBACK_COMPLETE ); if ((r = getdns_dict_get_list(response, "/replies_tree/0/answer", &answer))) fprintf(stderr, "Could not get \"answer\" section from first reply in the response"); else if ((r = getdns_list_get_length(answer, &n_answers))) fprintf(stderr, "Could not get replies_tree\'s length"); else for (i = 0; i < n_answers && r == GETDNS_RETURN_GOOD; i++) { getdns_dict *rr; getdns_bindata *dname; char *dname_str; if ((r = getdns_list_get_dict(answer, i, &rr))) fprintf(stderr, "Could not get rr %zu from answer section", i); else if (getdns_dict_get_bindata(rr, "/rdata/ptrdname", &dname)) continue; /* Not a PTR */ else if ((r = getdns_convert_dns_name_to_fqdn(dname, &dname_str))) fprintf(stderr, "Could not convert PTR dname to string"); else { printf("The dname is %s\n", dname_str); free(dname_str); } } if (r) { assert( r != GETDNS_RETURN_GOOD ); fprintf(stderr, ": %d\n", r); } getdns_dict_destroy(response); } int main() { getdns_return_t r; /* Holder for all function returns */ getdns_context *context = NULL; struct event_base *event_base = NULL; getdns_bindata address_type = { 4, (void *)"IPv4" }; getdns_bindata address_data = { 4, (void *)"\x08\x08\x08\x08" }; getdns_dict *address = NULL; getdns_dict *extensions = NULL; /* Could add things here to help identify this call */ char *userarg = NULL; getdns_transaction_t transaction_id; if ((r = getdns_context_create(&context, 1))) fprintf(stderr, "Trying to create the context failed"); else if (!(event_base = event_base_new())) fprintf(stderr, "Trying to create the event base failed.\n"); else if ((r = getdns_extension_set_libevent_base(context, event_base))) fprintf(stderr, "Setting the event base failed"); else if (!(address = getdns_dict_create())) fprintf(stderr, "Could not create address dict.\n"); else if ((r = getdns_dict_set_bindata(address, "address_type", &address_type))) fprintf(stderr, "Could not set address_type in address dict.\n"); else if ((r = getdns_dict_set_bindata(address, "address_data", &address_data))) fprintf(stderr, "Could not set address_data in address dict.\n"); else if ((r = getdns_hostname( context, address, extensions , userarg, &transaction_id, callback))) fprintf(stderr, "Error scheduling asynchronous request"); else if (event_base_dispatch(event_base) < 0) fprintf(stderr, "Error dispatching events\n"); /* Clean up */ if (event_base) event_base_free(event_base); if (context) getdns_context_destroy(context); /* Assuming we get here, leave gracefully */ exit(EXIT_SUCCESS); } getdns-1.5.1/spec/example/Makefile.in0000644000175000017500000001610113416117763014365 00000000000000# # @configure_input@ # # Copyright (c) 2013, Verisign, Inc., NLNet Labs # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the names of the copyright holders nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. package = @PACKAGE_NAME@ version = @PACKAGE_VERSION@ tarname = @PACKAGE_TARNAME@ distdir = $(tarname)-$(version) prefix = @prefix@ exec_prefix = @exec_prefix@ bindir = @bindir@ LIBTOOL = ../../libtool srcdir = @srcdir@ EXTENSION_LIBEVENT_EXT_LIBS=@EXTENSION_LIBEVENT_EXT_LIBS@ EXTENSION_LIBEVENT_LDFLAGS=@EXTENSION_LIBEVENT_LDFLAGS@ EXTENSION_LIBEVENT_LIB=../../src/libgetdns_ext_event.la CC=@CC@ CFLAGS=-I$(srcdir) -I$(srcdir)/../../src -I../../src @CFLAGS@ LDFLAGS=@LDFLAGS@ -L../../src LDLIBS=../../src/libgetdns.la @LIBS@ OBJS=example-all-functions.lo example-simple-answers.lo example-tree.lo example-synchronous.lo example-reverse.lo PROGRAMS=example-all-functions example-synchronous example-simple-answers example-tree example-reverse .SUFFIXES: .c .o .a .lo .h .c.o: $(CC) $(CFLAGS) -c $< -o $@ .c.lo: $(LIBTOOL) --quiet --tag=CC --mode=compile $(CC) $(CFLAGS) -c $< -o $@ default: all example: all all: $(PROGRAMS) $(OBJS): $(LIBTOOL) --quiet --tag=CC --mode=compile $(CC) $(CFLAGS) -c $(srcdir)/$(@:.lo=.c) -o $@ example-all-functions: example-all-functions.lo $(LIBTOOL) --tag=CC --mode=link $(CC) $(CFLAGS) $(LDFLAGS) $(LDLIBS) -o $@ example-all-functions.lo example-synchronous: example-synchronous.lo $(LIBTOOL) --tag=CC --mode=link $(CC) $(CFLAGS) $(LDFLAGS) $(LDLIBS) -o $@ example-synchronous.lo $(EXTENSION_LIBEVENT_LIB): @echo "***" @echo "*** Three examples from the specification need libevent." @echo "*** libevent was not found or usable at configure time." @echo "*** To compile and run all examples from the spec, make sure" @echo "*** libevent is available and usable during configuration." @echo "***" @false example-simple-answers: example-simple-answers.lo $(EXTENSION_LIBEVENT_LIB) $(LIBTOOL) --tag=CC --mode=link $(CC) $(CFLAGS) $(LDFLAGS) $(EXTENSION_LIBEVENT_LIB) $(EXTENSION_LIBEVENT_LDFLAGS) $(EXTENSION_LIBEVENT_EXT_LIBS) $(LDLIBS) -o $@ example-simple-answers.lo example-tree: example-tree.lo $(EXTENSION_LIBEVENT_LIB) $(LIBTOOL) --tag=CC --mode=link $(CC) $(CFLAGS) $(LDFLAGS) $(EXTENSION_LIBEVENT_LIB) $(EXTENSION_LIBEVENT_LDFLAGS) $(EXTENSION_LIBEVENT_EXT_LIBS) $(LDLIBS) -o $@ example-tree.lo example-reverse: example-reverse.lo $(EXTENSION_LIBEVENT_LIB) $(LIBTOOL) --tag=CC --mode=link $(CC) $(CFLAGS) $(LDFLAGS) $(EXTENSION_LIBEVENT_LIB) $(EXTENSION_LIBEVENT_LDFLAGS) $(EXTENSION_LIBEVENT_EXT_LIBS) $(LDLIBS) -o $@ example-reverse.lo clean: rm -f *.o *.lo $(PROGRAMS) rm -rf .libs distclean : clean rm -f Makefile config.status config.log rm -Rf autom4te.cache $(distdir): FORCE mkdir -p $(distdir)/src cp configure.ac $(distdir) cp configure $(distdir) cp Makefile.in $(distdir) cp src/Makefile.in $(distdir)/src distcheck: $(distdir).tar.gz gzip -cd $(distdir).tar.gz | tar xvf - cd $(distdir) && ./configure cd $(distdir) && $(MAKE) all cd $(distdir) && $(MAKE) check cd $(distdir) && $(MAKE) DESTDIR=$${PWD}/_inst install cd $(distdir) && $(MAKE) DESTDIR=$${PWD}/_inst uninstall @remaining="`find $${PWD}/$(distdir)/_inst -type f | wc -l`"; \ if test "$${remaining}" -ne 0; then echo "@@@ $${remaining} file(s) remaining in stage directory!"; \ exit 1; \ fi cd $(distdir) && $(MAKE) clean rm -rf $(distdir) @echo "*** Package $(distdir).tar.gz is ready for distribution" Makefile: $(srcdir)/Makefile.in ../../config.status cd ../.. && ./config.status spec/example/Makefile configure.status: configure cd ../.. && ./config.status --recheck .PHONY: clean depend: (cd $(srcdir) ; awk 'BEGIN{P=1}{if(P)print}/^# Dependencies/{P=0}' Makefile.in > Makefile.in.new ) (blddir=`pwd`; cd $(srcdir) ; gcc -MM -I. -I../../src -I"$$blddir"/../../src *.c | \ sed -e "s? $$blddir/? ?g" \ -e 's? \([a-z_-]*\)\.\([ch]\)? $$(srcdir)/\1.\2?g' \ -e 's? \$$(srcdir)/\.\./\.\./src/config\.h? ../../src/config.h?g' \ -e 's? $$(srcdir)/\.\./\.\./src/getdns/getdns_extra\.h? ../../src/getdns/getdns_extra.h?g' \ -e 's? \.\./\.\./src/getdns/getdns_ext_libevent\.h? $$(srcdir)/../../src/getdns/getdns_ext_libevent.h?g' \ -e 's? \.\./\.\./src/getdns/getdns_ext_libev\.h? $$(srcdir)/../../src/getdns/getdns_ext_libev.h?g' \ -e 's? \.\./\.\./src/getdns/getdns_ext_libuv\.h? $$(srcdir)/../../src/getdns/getdns_ext_libuv.h?g' \ -e 's? \.\./\.\./src/debug\.h? $$(srcdir)/../../src/debug.h?g' \ -e 's!\(.*\)\.o[ :]*!\1.lo \1.o: !g' >> Makefile.in.new ) (cd $(srcdir) ; diff Makefile.in.new Makefile.in && rm Makefile.in.new \ || mv Makefile.in.new Makefile.in ) # Dependencies for the examples example-all-functions.lo example-all-functions.o: $(srcdir)/example-all-functions.c $(srcdir)/getdns_libevent.h \ ../../src/config.h \ ../../src/getdns/getdns.h \ $(srcdir)/../../src/getdns/getdns_ext_libevent.h \ ../../src/getdns/getdns_extra.h example-reverse.lo example-reverse.o: $(srcdir)/example-reverse.c $(srcdir)/getdns_libevent.h \ ../../src/config.h \ ../../src/getdns/getdns.h \ $(srcdir)/../../src/getdns/getdns_ext_libevent.h \ ../../src/getdns/getdns_extra.h example-simple-answers.lo example-simple-answers.o: $(srcdir)/example-simple-answers.c $(srcdir)/getdns_libevent.h \ ../../src/config.h \ ../../src/getdns/getdns.h \ $(srcdir)/../../src/getdns/getdns_ext_libevent.h \ ../../src/getdns/getdns_extra.h example-synchronous.lo example-synchronous.o: $(srcdir)/example-synchronous.c $(srcdir)/getdns_core_only.h \ ../../src/getdns/getdns.h example-tree.lo example-tree.o: $(srcdir)/example-tree.c $(srcdir)/getdns_libevent.h \ ../../src/config.h \ ../../src/getdns/getdns.h \ $(srcdir)/../../src/getdns/getdns_ext_libevent.h \ ../../src/getdns/getdns_extra.h getdns-1.5.1/spec/example/example-all-functions.c0000644000175000017500000001664613416117763016711 00000000000000#include #include #include #include #include #include #define UNUSED_PARAM(x) ((void)(x)) /* The return values */ getdns_return_t retregular; char * retcharstar; /* The args */ int boolarg; char * charstararg; char ** charstarptrarg; getdns_callback_t callbackarg; uint16_t regulararg; uint16_t *regularptrarg; getdns_transaction_t txidarg; getdns_transaction_t * txidptrarg; getdns_namespace_t *namespaceptrarg; getdns_resolution_t resolutionarg; getdns_redirects_t redirectsarg; getdns_transport_t transportarg; getdns_append_name_t appendnamearg; getdns_data_type * datatypeptrarg; getdns_bindata ** bindataptrarg; getdns_dict * dictarg; getdns_bindata * bindataarg; getdns_list * listarg; getdns_dict ** dictptrarg; getdns_list ** listptrarg; size_t sizetarg; size_t * sizetptrarg; getdns_context *contextarg = NULL; uint8_t uint8arg; uint16_t uint16arg; uint32_t uint32arg; uint8_t * uint8ptrarg; uint16_t * uint16ptrarg; uint32_t * uint32ptrarg; void * arrayarg; void * userarg; void * allocfunctionarg(size_t foo) {UNUSED_PARAM(foo); return NULL; } void * reallocfunctionarg(void* foo, size_t bar) {UNUSED_PARAM(foo); UNUSED_PARAM(bar); return NULL; } void deallocfunctionarg(void* foo) {UNUSED_PARAM(foo);} void * extendedallocfunctionarg(void* userarg, size_t foo) {UNUSED_PARAM(userarg); UNUSED_PARAM(foo); return NULL; } void * extendedreallocfunctionarg(void* userarg, void* foo, size_t bar) {UNUSED_PARAM(userarg); UNUSED_PARAM(foo); UNUSED_PARAM(bar); return NULL; } void extendeddeallocfunctionarg(void* userarg, void* foo) {UNUSED_PARAM(userarg); UNUSED_PARAM(foo);} void setcallbackfunctionarg(getdns_context *foo1, getdns_context_code_t foo2) {UNUSED_PARAM(foo1);UNUSED_PARAM(foo2);} int main() { retregular = getdns_general( contextarg, charstararg, uint16arg, dictarg, arrayarg, txidptrarg, callbackarg ); retregular = getdns_address( contextarg, charstararg, dictarg, arrayarg, txidptrarg, callbackarg ); retregular = getdns_hostname( contextarg, dictarg, dictarg, arrayarg, txidptrarg, callbackarg ); retregular = getdns_service( contextarg, charstararg, dictarg, arrayarg, txidptrarg, callbackarg ); retregular = getdns_context_create( &contextarg, boolarg ); retregular = getdns_context_create_with_memory_functions( &contextarg, boolarg, allocfunctionarg, reallocfunctionarg, deallocfunctionarg ); retregular = getdns_context_create_with_extended_memory_functions( &contextarg, boolarg, userarg, extendedallocfunctionarg, extendedreallocfunctionarg, extendeddeallocfunctionarg ); getdns_context_destroy( contextarg ); retregular = getdns_cancel_callback( contextarg, txidarg ); retregular = getdns_general_sync( contextarg, charstararg, uint16arg, dictarg, &dictarg ); retregular = getdns_address_sync( contextarg, charstararg, dictarg, &dictarg ); retregular = getdns_hostname_sync( contextarg, dictarg, dictarg, &dictarg ); retregular = getdns_service_sync( contextarg, charstararg, dictarg, &dictarg ); retregular = getdns_list_get_length(listarg, sizetptrarg); retregular = getdns_list_get_data_type(listarg, sizetarg, datatypeptrarg); retregular = getdns_list_get_dict(listarg, sizetarg, dictptrarg); retregular = getdns_list_get_list(listarg, sizetarg, listptrarg); retregular = getdns_list_get_bindata(listarg, sizetarg, bindataptrarg); retregular = getdns_list_get_int(listarg, sizetarg, uint32ptrarg); retregular = getdns_dict_get_names(dictarg, listptrarg); retregular = getdns_dict_get_data_type(dictarg, charstararg, datatypeptrarg); retregular = getdns_dict_get_dict(dictarg, charstararg, dictptrarg); retregular = getdns_dict_get_list(dictarg, charstararg, listptrarg); retregular = getdns_dict_get_bindata(dictarg, charstararg, bindataptrarg); retregular = getdns_dict_get_int(dictarg, charstararg, uint32ptrarg); listarg = getdns_list_create(); listarg = getdns_list_create_with_context(contextarg); listarg = getdns_list_create_with_memory_functions( allocfunctionarg, reallocfunctionarg, deallocfunctionarg ); listarg = getdns_list_create_with_extended_memory_functions( userarg, extendedallocfunctionarg, extendedreallocfunctionarg, extendeddeallocfunctionarg ); getdns_list_destroy(listarg); retregular = getdns_list_set_dict(listarg, sizetarg, dictarg); retregular = getdns_list_set_list(listarg, sizetarg, listarg); retregular = getdns_list_set_bindata(listarg, sizetarg, bindataarg); retregular = getdns_list_set_int(listarg, sizetarg, uint32arg); dictarg = getdns_dict_create(); dictarg = getdns_dict_create_with_context(contextarg); dictarg = getdns_dict_create_with_memory_functions( allocfunctionarg, reallocfunctionarg, deallocfunctionarg ); dictarg = getdns_dict_create_with_extended_memory_functions( userarg, extendedallocfunctionarg, extendedreallocfunctionarg, extendeddeallocfunctionarg ); getdns_dict_destroy(dictarg); retregular = getdns_dict_set_dict(dictarg, charstararg, dictarg); retregular = getdns_dict_set_list(dictarg, charstararg, listarg); retregular = getdns_dict_set_bindata(dictarg, charstararg, bindataarg); retregular = getdns_dict_set_int(dictarg, charstararg, uint32arg); retregular = getdns_dict_remove_name(dictarg, charstararg); retregular = getdns_convert_fqdn_to_dns_name( charstararg, bindataptrarg ); retregular = getdns_convert_dns_name_to_fqdn( bindataarg, charstarptrarg ); retcharstar = getdns_convert_ulabel_to_alabel( charstararg ); retcharstar = getdns_convert_alabel_to_ulabel( charstararg ); retregular = getdns_validate_dnssec( listarg, listarg, listarg ); retcharstar = getdns_pretty_print_dict( dictarg ); retcharstar = getdns_display_ip_address( bindataarg ); retregular = getdns_context_set_context_update_callback( contextarg, setcallbackfunctionarg ); retregular = getdns_context_set_resolution_type( contextarg, resolutionarg ); retregular = getdns_context_set_namespaces( contextarg, sizetarg, namespaceptrarg ); retregular = getdns_context_set_dns_transport( contextarg, transportarg ); retregular = getdns_context_set_limit_outstanding_queries( contextarg, uint16arg ); retregular = getdns_context_set_timeout( contextarg, uint16arg ); retregular = getdns_context_set_follow_redirects( contextarg, redirectsarg ); retregular = getdns_context_set_dns_root_servers( contextarg, listarg ); retregular = getdns_context_set_append_name( contextarg, appendnamearg ); retregular = getdns_context_set_suffix( contextarg, listarg ); retregular = getdns_context_set_dnssec_trust_anchors( contextarg, listarg ); retregular = getdns_context_set_dnssec_allowed_skew( contextarg, uint16arg ); retregular = getdns_context_set_upstream_recursive_servers( contextarg, listarg ); retregular = getdns_context_set_edns_maximum_udp_payload_size( contextarg, uint16arg ); retregular = getdns_context_set_edns_extended_rcode( contextarg, uint8arg ); retregular = getdns_context_set_edns_version( contextarg, uint8arg ); retregular = getdns_context_set_edns_do_bit( contextarg, uint8arg ); retregular = getdns_context_set_memory_functions( contextarg, allocfunctionarg, reallocfunctionarg, deallocfunctionarg ); retregular = getdns_context_set_extended_memory_functions( contextarg, userarg, extendedallocfunctionarg, extendedreallocfunctionarg, extendeddeallocfunctionarg ); return(0); } /* End of main() */ getdns-1.5.1/spec/index.html0000644000175000017500000046377713416117763012713 00000000000000 DNS API Description

Description of the getdns API

Originally edited by Paul Hoffman

Currently maintained by the getdns team

Document version: "getdns December 2015"

This document describes a modern asynchronous DNS API. This new API is intended to be useful to application developers and operating system distributors as a way of making all types of DNS information easily available in many types of programs. The major features of this new API are:

  • Full support for event-driven programming
  • Supports DNSSEC in multiple ways
  • Mirroring of the resolution in getaddrinfo()
  • Easily supports all RRtypes, even those yet to be defined

There is more background into the design and future goals of this API later in this document.

This document was discussed on the getdns-api mailing list; future versions of the API might be discussed there as well. (If you want to contact the editors off-list, please send mail to team@getdnsapi.net.)

1. The getdns Async Functions

The API has four async functions:

  • getdns_address for doing getaddrinfo()-like address lookups
  • getdns_hostname for doing getnameinfo()-like name lookups
  • getdns_service for getting results from SRV lookups
  • getdns_general for looking up any type of DNS record

1.1 getdns_general()

getdns_return_t getdns_general( getdns_context *context, const char *name, uint16_t request_type, getdns_dict *extensions, void *userarg, getdns_transaction_t *transaction_id, getdns_callback_t callbackfn );

context

A pointer to the DNS context that is to be used with this call. DNS contexts are described later in this document. Note that a context must be created before calling the function.

*name

This is a null-terminted string consisting of an ASCII-based domain name to be looked up. The values here follow the rules in section 2.1 of RFC 4343 to allow non-ASCII octets and special characters in labels.

request_type

Specifies the RRtype for the query; the RRtype numbers are listed in the IANA registry. For example, to get the NS records, request_type would be 2. The API also has defined macros for most of the RRtypes by name; the definition names all start with "GETDNS_RRTYPE_". For example, to get the NS records, you can also set the request_type to GETDNS_RRTYPE_NS. (The full list of request types is always here.)

*extensions

Specifies the extensions for this request; the value may be NULL if there are no extensions. See the section below for information on how to specify the extensions used for a request.

*userarg

A void* that is passed to the function, which the function returns to the callback function untouched. userarg can be used by the callback function for any user-specific data needed. This can be NULL.

*transaction_id

A pointer to a value that is filled in by the function to identify the callback being made. This pointer can be NULL, in which case it is ignored and no value is assigned. The getdns_cancel_callback() function uses the transaction_id to determine which callback is to be cancelled. If the function fails, transaction_id is set to 0.

*callbackfn

A pointer to a callback function that is defined by the application. Typically, the callback function will do all the processing on the results from the API. The parameters of the callback are defined below. This really needs to be a pointer to a function (and not something like NULL); otherwise, the results are unpredictable.

The async getdns functions return GETDNS_RETURN_GOOD if the call was properly formatted. It returns GETDNS_RETURN_BAD_DOMAIN_NAME if the API determines that the name passed to the function was bad, GETDNS_RETURN_BAD_CONTEXT if the context has internal deficiencies, GETDNS_RETURN_NO_SUCH_EXTENSION if one or more extensions do not exist, or GETDNS_RETURN_EXTENSION_MISFORMAT if the contents of one or more of the extensions is incorrect. All of the return values are given later in this document.

1.2 getdns_address()

getdns_return_t getdns_address( getdns_context *context, const char *name, getdns_dict *extensions, void *userarg, getdns_transaction_t *transaction_id, getdns_callback_t callbackfn );

There are three critical differences between getdns_address() and getdns_general() beyond the missing request_type argument:

  • In getdns_address(), the name argument can only take a host name.
  • You do not need to include a return_both_v4_and_v6 extension with the call in getdns_address(): it will always return both IPv4 and IPv6 addresses.
  • getdns_address() always uses all of namespaces from the context (to better emulate getaddrinfo()), while getdns_general() only uses the DNS namespace.

1.3 getdns_hostname()

getdns_return_t getdns_hostname( getdns_context *context, getdns_dict *address, getdns_dict *extensions, void *userarg, getdns_transaction_t *transaction_id, getdns_callback_t callbackfn );

The address is given as a getdns_dict data structure (defined below). The list must have two names: address_type (whose value is a bindata; it is currently either "IPv4" or "IPv6" (which are case-sensitive)) and address_data (whose value is a bindata).

1.4 getdns_service()

getdns_return_t getdns_service( getdns_context *context, const char *name, getdns_dict *extensions, void *userarg, getdns_transaction_t *transaction_id, getdns_callback_t callbackfn );

name must be a domain name for an SRV lookup; the call returns the relevant SRV information for the name.

1.5 Callback Functions for getdns

A call to the async getdns functions typically returns before any network or file I/O occurs. After the API marshalls all the needed information, it calls the callback function that was passed by the application. The callback function might be called at any time, even before the calling function has returned. The API guarantees that the callback will be called exactly once unless the calling function returned an error, in which case the callback function is never called.

The getdns calling function calls the callback with the parameters defined as follows:

typedef void (*getdns_callback_t)( getdns_context *context, getdns_callback_type_t callback_type, getdns_dict *response, void *userarg, getdns_transaction_t transaction_id);

context

The DNS context that was used in the calling function. See below for a description of the basic use of contexts, and later for more advanced use.

callback_type

Supplies the reason for the callback. See below for the codes and reasons.

*response

A response object with the response data. This is described below. The application is responsible for cleaning up the response object with getdns_dict_destroy.

*userarg

Identical to the *userarg passed to the calling function.

transaction_id

The transaction identifier that was assigned by the calling function.

The following are the values for callback_type.

GETDNS_CALLBACK_COMPLETE

The response has the requested data in it

GETDNS_CALLBACK_CANCEL

The calling program cancelled the callback; response is NULL

GETDNS_CALLBACK_TIMEOUT

The requested action timed out; response is filled in with empty structures

GETDNS_CALLBACK_ERROR

The requested action had an error; response is NULL

1.6 Setting Up The DNS Context

Calls to getdns functions require a DNS context, which is a group of API settings that affect how DNS calls are made. For most applications, a default context is sufficient.

To create a new DNS context, use the function:

getdns_return_t getdns_context_create( getdns_context **context, int set_from_os );

The call to getdns_context_create immediately returns a context that can be used with other API calls; that context contains the API's default values. Most applications will want set_from_os set to 1.

getdns_return_t getdns_context_create_with_memory_functions( getdns_context **context, int set_from_os, void *(*malloc)(size_t), void *(*realloc)(void *, size_t), void (*free)(void *) ); getdns_return_t getdns_context_create_with_extended_memory_functions( getdns_context **context, int set_from_os, void *userarg, void *(*malloc)(void *userarg, size_t), void *(*realloc)(void *userarg, void *, size_t), void (*free)(void *userarg, void *) );

To clean up the context, including cleaning up all outstanding transactions that were called using this context, use the function:

void getdns_context_destroy( getdns_context *context );

When getdns_context_destroy() returns, the application knows that all outstanding transactions associated with this context will have been called; callbacks that had not been called before getdns_context_destroy() was called will be called with a callback_type of GETDNS_CALLBACK_CANCEL. getdns_context_destroy() returns after all of the needed cleanup is done and callbacks are made.

1.7 Canceling a Callback

To cancel an outstanding callback, use the following function.

getdns_return_t getdns_cancel_callback( getdns_context *context, getdns_transaction_t transaction_id );

This causes the API to call the callback with a callback_type of GETDNS_CALLBACK_CANCEL if the callback for this transaction_id has not already been called. This will cancel the callback regardless of what the original call was doing (such as in the middle of a DNS request, while DNSSEC validation is happening, and so on). The callback code for cancellation should clean up any memory related to the identified call, such as to deallocate the memory for the userarg. getdns_cancel_callback() may return immediately, even before the callback finishes its work and returns. Calling getdns_cancel_callback() with a transaction_id of a callback that has already been called or an unknown transaction_id returns GETDNS_RETURN_UNKNOWN_TRANSACTION; otherwise, getdns_cancel_callback() returns GETDNS_RETURN_GOOD.

1.8 Event-driven Programs

Event-driven programs (sometimes called "async programs") require an event base and event loop (among other things). Different event libraries have different structures or the event base. Because of this, there is no standard method to set the event base in the DNS API: those are all added as extensions. The API is distributed as a core package and one or more sets of extensions to align with event libraries. It is mandatory to use one of the extension functions to set the event base in the DNS context; this is required before calling any event-driven calls like the getdns functions.

Each implementation of the DNS API will specify an extension function that tells the DNS context which event base is being used. For example, one implementation of this API that uses the libevent event library might name this function "getdns_extension_set_libevent_base()" while another might name it "getdns_extension_set_eventbase_for_libevent()"; the two extension functions could have very different calling patterns and return values. Thus, the application developer must read the API documentation (not just this design document) in order to determine what extension function to use to tell the API the event base to use.

The structure of a typical event-driven application might look like the following pseudocode. The code in italics is specific to the event mechanism.

Includes for one or more regular C libraries
An include for the getdns library specific to the event library you use
Definition of your callback function
    Get the DNS data from the allocated pointer
    Process that data
    Check for errors
Definition of main()
    Create context
    Set up your event base
    Point the context to your event base
    Set up the getdns call arguments
    Make the getdns call
    Check if the getdns return is good
    Destroy the context
    Exit

The API does not have direct support for a polling interface. Instead, the callback interface is specifically designed to allow an application that wants to process results in polling instead of in callbacks to be able to create its own polling interface fairly trivially. Such a program would create a data structure for the calls, including their transaction_id and userarg. The userarg could be the polling data structure or have a pointer to it. The application would have just one callback function for all requests, and that function would copy the response into application memory, update the data structure based on the transaction_id index, and return from the callback. The polling code could then check the data structure for any updates at its leisure.

1.9 Calling the API Synchronously (Without Events)

There are functions parallel to the four getdns async functions, except that there is no callback. That is, when an application calls one of these synchronous functions, the API gathers all the required information and then returns the result. The value returned is exactly the same as the response returned in the callback if you had used the async version of the function.

getdns_return_t getdns_general_sync( getdns_context *context, const char *name, uint16_t request_type, getdns_dict *extensions, getdns_dict **response );
getdns_return_t getdns_address_sync( getdns_context *context, const char *name, getdns_dict *extensions, getdns_dict **response );
getdns_return_t getdns_hostname_sync( getdns_context *context, getdns_dict *address, getdns_dict *extensions, getdns_dict **response );
getdns_return_t getdns_service_sync( getdns_context *context, const char *name, getdns_dict *extensions, getdns_dict **response );

When you are done with the data in the response, use the following function so that the API can free the memory from its internal pool.

void getdns_dict_destroy( getdns_dict *response );

2. Data structures in the API

The API returns data structures. The data structure is not a representational language like JSON: it is really just a data structure. Data structures can have four types of members:

  • list is an ordered list, like JSON and Python lists. The members of the list can be any of the four data types.
  • dict is a name-value pair, like a JSON object or Python dict. The name is a string literal, and the value can be any of the four data types. The order of the name-value pairs in a dict is not important.
  • int is an integer compatible with uint32_t.
  • bindata is a struct to hold binary data. It is defined as { size_t size; uint8_t *binary_stuff; }.

The API comes with helper functions to get data from the list and dict data types:

/* Lists: get the length, get the data_type of the value at a given position, and get the data at a given position */ getdns_return_t getdns_list_get_length(const getdns_list *list, size_t *answer); getdns_return_t getdns_list_get_data_type(const getdns_list *list, size_t index, getdns_data_type *answer); getdns_return_t getdns_list_get_dict(const getdns_list *list, size_t index, getdns_dict **answer); getdns_return_t getdns_list_get_list(const getdns_list *list, size_t index, getdns_list **answer); getdns_return_t getdns_list_get_bindata(const getdns_list *list, size_t index, getdns_bindata **answer); getdns_return_t getdns_list_get_int(const getdns_list *list, size_t index, uint32_t *answer); /* Dicts: get the list of names, get the data_type of the value at a given name, and get the data at a given name */ getdns_return_t getdns_dict_get_names(const getdns_dict *dict, getdns_list **answer); getdns_return_t getdns_dict_get_data_type(const getdns_dict *dict, const char *name, getdns_data_type *answer); getdns_return_t getdns_dict_get_dict(const getdns_dict *dict, const char *name, getdns_dict **answer); getdns_return_t getdns_dict_get_list(const getdns_dict *dict, const char *name, getdns_list **answer); getdns_return_t getdns_dict_get_bindata(const getdns_dict *dict, const char *name, getdns_bindata **answer); getdns_return_t getdns_dict_get_int(const getdns_dict *dict, const char *name, uint32_t *answer);

All of these helper getter functions return GETDNS_RETURN_GOOD if the call is successful. The list functions will return GETDNS_RETURN_NO_SUCH_LIST_ITEM if the index argument is out of range; the dict functions will return GETDNS_RETURN_NO_SUCH_DICT_NAME if the name argument doesn't exist in the dict. The functions also return GETDNS_RETURN_WRONG_TYPE_REQUESTED if the requested data type doesn't match the contents of the indexed argument or name.

This document uses graphical representations of data structures. It is important to note that this is only a graphical representation; the brackets, commas, quotation marks, comments, and so on are not part of the data. Also, this document uses macro names instead of some of the int arguments; of course, the data structures have the actual int in them.

The getdns_dict_get_names helper function creates a newly created list containing the names in a dict. The caller is responsible for disposing this list.

The helper getter functions return references to getdns_dict, getdns_list and getdns_bindata data structures. The user must not directly destroy these retrieved "child" data structures; instead, they will automatically be destroyed when the containing "parent" data structure is destroyed. Because of this, retrieved "child" data structures cannot be used any more after the containing "parent" data structure has been destroyed.

When the name parameter to the getdns_dict_get_ functions, starts with a '/' (%x2F) character, it is interpreted as a JSON Pointer as described in RFC 6901, and will then be used to dereference the nested data structures to get to the requested data type.

2.1 Creating Data Structures

Some of the features of the API require that you create your own data structures to be used in arguments passed to the API. For example, if you want to use any extensions for the calling functions, you need to create a dict. The requisite functions are:

/* Lists: create, destroy, and set the data at a given position */ getdns_list * getdns_list_create(); getdns_list * getdns_list_create_with_context( getdns_context *context ); getdns_list * getdns_list_create_with_memory_functions( void *(*malloc)(size_t), void *(*realloc)(void *, size_t), void (*free)(void *) ); getdns_list * getdns_list_create_with_extended_memory_functions( void *userarg, void *(*malloc)(void *userarg, size_t), void *(*realloc)(void *userarg, void *, size_t), void (*free)(void *userarg, void *) ); void getdns_list_destroy(getdns_list *list); getdns_return_t getdns_list_set_dict(getdns_list *list, size_t index, const getdns_dict *child_dict); getdns_return_t getdns_list_set_list(getdns_list *list, size_t index, const getdns_list *child_list); getdns_return_t getdns_list_set_bindata(getdns_list *list, size_t index, const getdns_bindata *child_bindata); getdns_return_t getdns_list_set_int(getdns_list *list, size_t index, uint32_t child_uint32); /* Dicts: create, destroy, and set the data at a given name */ getdns_dict * getdns_dict_create(); getdns_dict * getdns_dict_create_with_context( getdns_context *context ); getdns_dict * getdns_dict_create_with_memory_functions( void *(*malloc)(size_t), void *(*realloc)(void *, size_t), void (*free)(void *) ); getdns_dict * getdns_dict_create_with_extended_memory_functions( void *userarg, void *(*malloc)(void *userarg, size_t), void *(*realloc)(void *userarg, void *, size_t), void (*free)(void *userarg, void *) ); void getdns_dict_destroy(getdns_dict *dict); getdns_return_t getdns_dict_set_dict(getdns_dict *dict, const char *name, const getdns_dict *child_dict); getdns_return_t getdns_dict_set_list(getdns_dict *dict, const char *name, const getdns_list *child_list); getdns_return_t getdns_dict_set_bindata(getdns_dict *dict, const char *name, const getdns_bindata *child_bindata); getdns_return_t getdns_dict_set_int(getdns_dict *dict, const char *name, uint32_t child_uint32); getdns_return_t getdns_dict_remove_name(getdns_dict *dict, const char *name);

Lists are extended with the getdns_list_set_ calls with the index set to the size of the list (such as 0 for an empty list). Dicts are extended with the getdns_dict_set_ calls with the name set to a name that does not yet exist. Name-value pairs are removed with getdns_dict_remove_name().

These helper setter functions return GETDNS_RETURN_GOOD if the call is successful. The functions return GETDNS_RETURN_WRONG_TYPE_REQUESTED if the requested data type doesn't match the contents of the indexed argument or name. The list functions will return GETDNS_RETURN_NO_SUCH_LIST_ITEM if the index argument is higher than the length of the list. getdns_dict_remove_name() will return GETDNS_RETURN_NO_SUCH_DICT_NAME if the name argument doesn't exist in the dict.

The helper setter functions store copies of the given "child" values. It is the responsibility of the caller to dispose of the original values.

When the name parameter to the getdns_dict_set_ functions, starts with a '/' (%x2F) character, it is interpreted as a JSON Pointer as described in RFC 6901, and will then be used to dereference the nested data structures to set the given value at the specified name or list index.

3. Extensions

Extensions are dict data structures. The names in the dict are the names of the extensions. The definition of each extension describes the value associated with the name. For most extensions, it is an on-off boolean, and the value is GETDNS_EXTENSION_TRUE. (There is not currently a good reason to specify an extension name and give it a value of GETDNS_EXTENSION_FALSE, but that is allowed by the API.)

For example, to create a dict for extensions and specify the extension to only return results that have been validated with DNSSEC, you might use:

/* . . . */
getdns_dict * extensions = getdns_dict_create();
ret = getdns_dict_set_int(extensions, "dnssec_return_only_secure", GETDNS_EXTENSION_TRUE);
/* . . . Do some processing with the extensions and results . . . */
/* Remember to clean up memory*/
getdns_dict_destroy(extensions);

The extensions described in this section are are:

  • dnssec_return_status
  • dnssec_return_only_secure
  • dnssec_return_validation_chain
  • return_both_v4_and_v6
  • add_opt_parameters
  • add_warning_for_bad_dns
  • specify_class
  • return_call_reporting

3.1 Extensions for DNSSEC

If an application wants the API to do DNSSEC validation for a request, it must set one or more DNSSEC-related extensions. Note that the default is for none of these extensions to be set and the API will not perform DNSSEC. Note that getting DNSSEC results can take longer in a few circumstances.

To return the DNSSEC status for each DNS record in the replies_tree list, use the dnssec_return_status extension. The extension's value (an int) is set to GETDNS_EXTENSION_TRUE to cause the returned status to have the name dnssec_status (an int) added to the other names in the record's dict ("header", "question", and so on). The values for that name are GETDNS_DNSSEC_SECURE, GETDNS_DNSSEC_BOGUS, GETDNS_DNSSEC_INDETERMINATE, and GETDNS_DNSSEC_INSECURE. Thus, a reply might look like:

    {     # This is the first reply
      "dnssec_status": GETDNS_DNSSEC_INDETERMINATE,
      "header": { "id": 23456, "qr": 1, "opcode": 0, ... },
      . . .

If instead of returning the status, you want to only see secure results, use the dnssec_return_only_secure extension. The extension's value (an int) is set to GETDNS_EXTENSION_TRUE to cause only records that the API can validate as secure with DNSSEC to be returned in the replies_tree and replies_full lists. No additional names are added to the dict of the record; the change is that some records might not appear in the results. When this context option is set, if the API receives DNS replies but none are determined to be secure, the error code at the top level of the response object is GETDNS_RESPSTATUS_NO_SECURE_ANSWERS.

Applications that want to do their own validation will want to have the DNSSEC-related records for a particular response. Use the dnssec_return_validation_chain extension. The extension's value (an int) is set to GETDNS_EXTENSION_TRUE to cause a set of additional DNSSEC-related records needed for validation to be returned in the response object. This set comes as validation_chain (a list) at the top level of the response object. This list includes all resource record dicts for all the resource records (DS, DNSKEY and their RRSIGs) that are needed to perform the validation from the root up. Thus, a reply might look like:

{     # This is the response object
  "validation_chain":
  [ { "name": <bindata for .>,
      "type": GETDNS_RRTYPE_DNSKEY,
      "rdata": { "flags": 256, . . . },
      . . . 
    },
    { "name": <bindata for .>,
      "type": GETDNS_RRTYPE_DNSKEY,
      "rdata": { "flags": 257, . . . },
      . . .
    },
    { "name": <bindata for .>,
      "type": GETDNS_RRTYPE_RRSIG,
      "rdata": { "signers_name": <bindata for .>,
                 "type_covered": GETDNS_RRTYPE_DNSKEY,
                 . . .
               },
    },
    { "name": <bindata for com.>,
      "type": GETDNS_RRTYPE_DS,
      . . .
    },
    { "name": <bindata for com.>,
      "type": GETDNS_RRTYPE_RRSIG
      "rdata": { "signers_name": <bindata for .>,
                 "type_covered": GETDNS_RRTYPE_DS,
                 . . .
               },
      . . .
    },
    { "name": <bindata for com.>,
      "type": GETDNS_RRTYPE_DNSKEY
      "rdata": { "flags": 256, . . . },
      . . .
    },
    { "name": <bindata for com.>,
      "type": GETDNS_RRTYPE_DNSKEY
      "rdata": { "flags": 257, . . . },
      . . .
    },
    { "name": <bindata for com.>,
      "type": GETDNS_RRTYPE_RRSIG
      "rdata": { "signers_name": <bindata for com.>,
                 "type_covered": GETDNS_RRTYPE_DNSKEY,
                 . . .
               },
      . . .
    },
    { "name": <bindata for example.com.>,
      "type": GETDNS_RRTYPE_DS,
      . . .
    },
    { "name": <bindata for example.com.>,
      "type": GETDNS_RRTYPE_RRSIG
      "rdata": { "signers_name": <bindata for com.>,
                 "type_covered": GETDNS_RRTYPE_DS,
                 . . .
               },
      . . .
    },
    { "name": <bindata for example.com.>,
      "type": GETDNS_RRTYPE_DNSKEY
      "rdata": { "flags": 257, ... },
      . . .
    },
    . . .
  ]
  "replies_tree":
  [
  . . .

Implementations not capable of performing DNSSEC in stub resolution mode may indicate this by not performing a request and instead return an error of GETDNS_RETURN_DNSSEC_WITH_STUB_DISALLOWED when using a context in which stub resolution is set, and having any of the dnssec_return_status, dnssec_return_only_secure, or dnssec_return_validation_chain extensions specified.

3.2 Returning Both IPv4 and IPv6 Responses

Many applications want to get both IPv4 and IPv6 addresses in a single call so that the results can be processed together. The getdns_address and getdns_address_sync functions are able to do this automatically. If you are using the getdns_general or getdns_general_sync function, you can enable this with the return_both_v4_and_v6 extension. The extension's value (an int) is set to GETDNS_EXTENSION_TRUE to cause the results to be the lookup of either A or AAAA records to include any A and AAAA records for the queried name (otherwise, the extension does nothing). These results are expected to be used with Happy Eyeballs systems that will find the best socket for an application.

3.3 Setting Up OPT Resource Records

For lookups that need an OPT resource record in the Additional Data section, use the add_opt_parameters extension. The extension's value (a dict) contains the parameters; these are described in more detail in RFC 6891. They are:

  • maximum_udp_payload_size (an int), a value between 512 and 65535; if not specified, this defaults to those from the DNS context
  • extended_rcode (an int), a value between 0 and 255; if not specified, this defaults to those from the DNS context
  • version (an int), a value between 0 and 255; if not specified, this defaults to 0
  • do_bit (an int), a value between 0 and 1; if not specified, this defaults to those from the DNS context
  • options (a list) contains dicts for each option to be specified. Each list time contains two names: option_code (an int) and option_data (a bindata). The API marshalls the entire set of options into a properly-formatted RDATA for the resource record.

It is very important to note that the OPT resource record specified in the add_opt_parameters extension might not be the same the one that the API sends in the query. For example, if the application also includes any of the DNSSEC extensions, the API will make sure that the OPT resource record sets the resource record appropriately, making the needed changes to the settings from the add_opt_parameters extension.

The use of this extension can conflict with the values in the DNS context. For example, the default for an OS might be a maximum payload size of 65535, but the extension might specify 1550. In such a case, the API will honor the values stated in the extension, but will honor the values from the DNS context if values are not given in the extension.

3.4 Getting Warnings for Responses that Violate the DNS Standard

To receive a warning if a particular response violates some parts of the DNS standard, use the add_warning_for_bad_dns extension. The extension's value (an int) is set to GETDNS_EXTENSION_TRUE to cause each reply in the replies_tree to contain an additional name, bad_dns (a list). The list is zero or more ints that indicate types of bad DNS found in that reply. The list of values is:

GETDNS_BAD_DNS_CNAME_IN_TARGET

A DNS query type that does not allow a target to be a CNAME pointed to a CNAME

GETDNS_BAD_DNS_ALL_NUMERIC_LABEL

One or more labels in a returned domain name is all-numeric; this is not legal for a hostname

GETDNS_BAD_DNS_CNAME_RETURNED_FOR_OTHER_TYPE

A DNS query for a type other than CNAME returned a CNAME response

3.5 Using Other Class Types

The vast majority of DNS requests are made with the Internet (IN) class. To make a request in a different DNS class, use, the specify_class extension. The extension's value (an int) contains the class number. Few applications will ever use this extension.

3.6 Extensions Relating to the API

An application might want to see debugging information for queries such as the length of time it takes for each query to return to the API. Use the return_call_reporting extension. The extension's value (an int) is set to GETDNS_EXTENSION_TRUE to add the name call_reporting (a list) to the top level of the response object. Each member of the list is a dict that represents one call made for the call to the API. Each member has the following names:

  • query_name (a bindata) is the name that was sent
  • query_type (an int) is the type that was queried for
  • query_to (a bindata) is the address to which the query was sent
  • run_time/ms (a bindata) is the difference between the time the successful query started and ended in milliseconds, represented as a uint32_t (this does not include time taken for connection set up or transport fallback)
  • entire_reply (a bindata) is the entire response received
  • dnssec_result (an int) is the DNSSEC status, or GETDNS_DNSSEC_NOT_PERFORMED if DNSSEC validation was not performed

4. Response Data from Queries

The callback function contains a pointer to a response object. A response object is always a dict. The response object always contains at least three names: replies_full (a list) and replies_tree (a list), and status (an int). replies_full is a list of DNS replies (each is bindata) as they appear on the wire. replies_tree is a list of DNS replies (each is a dict) with the various part of the reply parsed out. status is a status code for the query.

Because the API might be extended in the future, a response object might also contain names other than replies_full, replies_tree, and status. Similarly, any of the dicts described here might be extended in later versions of the API. Thus, an application using the API must not assume that it knows all possible names in a dict.

The following lists the status codes for response objects. Note that, if the status is that there are no responses for the query, the lists in replies_full and replies_tree will have zero length.

GETDNS_RESPSTATUS_GOOD

At least one response was returned

GETDNS_RESPSTATUS_NO_NAME

Queries for the name yielded all negative responses

GETDNS_RESPSTATUS_ALL_TIMEOUT

All queries for the name timed out

GETDNS_RESPSTATUS_NO_SECURE_ANSWERS

The context setting for getting only secure responses was specified, and at least one DNS response was received, but no DNS response was determined to be secure through DNSSEC.

GETDNS_RESPSTATUS_ALL_BOGUS_ANSWERS

The context setting for getting only secure responses was specified, and at least one DNS response was received, but all received responses for the requested name were bogus.

The top level of replies_tree can optionally have the following names: canonical_name (a bindata), intermediate_aliases (a list), answer_ipv4_address (a bindata), answer_ipv6_address (a bindata), and answer_type (an int).

  • The value of canonical_name is the name that the API used for its lookup. It is in FQDN presentation format.
  • The values in the intermediate_aliases list are domain names from any CNAME or unsynthesized DNAME found when resolving the original query. The list might have zero entries if there were no CNAMEs in the path. These may be useful, for example, for name comparisons when following the rules in RFC 6125.
  • The value of answer_ipv4_address and answer_ipv6_address are the addresses of the server from which the answer was received.
  • The value of answer_type is the type of name service that generated the response. The values are:

GETDNS_NAMETYPE_DNS

Normal DNS (RFC 1035)

GETDNS_NAMETYPE_WINS

The WINS name service (some reference needed)

If the call was getdns_address or getdns_address_sync, the top level of replies_tree has an additional name, just_address_answers (a list). The value of just_address_answers is a list that contains all of the A and AAAA records from the answer sections of any of the replies, in the order they appear in the replies. Each item in the list is a dict with at least two names: address_type (whose value is a bindata; it is currently either "IPv4" or "IPv6") and address_data (whose value is a bindata). Note that the dnssec_return_only_secure extension affects what will appear in the just_address_answers list. Also note if later versions of the DNS return other address types, those types will appear in this list as well.

The API can make service discovery through SRV records easier. If the call was getdns_service or getdns_service_sync, the top level of replies_tree has an additional name, srv_addresses (a list). The list is ordered by priority and weight based on the weighting algorithm in RFC 2782, lowest priority value first. Each element of the list is dict has at least two names: port and domain_name. If the API was able to determine the address of the target domain name (such as from its cache or from the Additional section of responses), the dict for an element will also contain address_type (whose value is a bindata; it is currently either "IPv4" or "IPv6") and address_data (whose value is a bindata). Note that the dnssec_return_only_secure extension affects what will appear in the srv_addresses list.

4.1 Structure of DNS replies_tree

The names in each entry in the the replies_tree list for DNS responses include header (a dict), question (a dict), answer (a list), authority (a list), and additional (a list), corresponding to the sections in the DNS message format. The answer, authority, and additional lists each contain zero or more dicts, with each dict in each list representing a resource record.

The names in the header dict are all the fields from Section 4.1.1. of RFC 1035. They are: id, qr, opcode, aa, tc, rd, ra, z, rcode, qdcount, ancount, nscount, and arcount. All are ints.

The names in the question dict are the three fields from Section 4.1.2. of RFC 1035: qname (a bindata), qtype (an int), and qclass (an int).

Resource records are a bit different than headers and question sections in that the RDATA portion often has its own structure. The other names in the resource record dicts are name (a bindata), type (an int), class (an int), ttl (an int) and rdata (a dict); there is no name equivalent to the RDLENGTH field. The OPT resource record does not have the class and the ttl name, but in stead provides udp_payload_size (an int), extended_rcode (an int), version (an int), do (an int), and z (an int).

The rdata dict has different names for each response type. There is a complete list of the types defined in the API. For names that end in "-obsolete" or "-unknown", the bindata is the entire RDATA field. For example, the rdata for an A record has a name ipv4_address (a bindata); the rdata for an SRV record has the names priority (an int), weight (an int), port (an int), and target (a bindata).

Each rdata dict also has a rdata_raw field (a bindata). This is useful for types not defined in this version of the API. It also might be of value if a later version of the API allows for additional parsers. Thus, doing a query for types not known by the API still will return a result: an rdata with just a rdata_raw.

It is expected that later extensions to the API will give some DNS types different names. It is also possible that later extensions will change the names for some of the DNS types listed above.

For example, a response to a getdns_address() call for www.example.com would look something like this:

{     # This is the response object
  "replies_full": [ <bindata of the first response>, <bindata of the second response> ],
  "just_address_answers":
  [
    {
      "address_type": <bindata of "IPv4">,
      "address_data": <bindata of 0x0a0b0c01>,
    },
    {
      "address_type": <bindata of "IPv6">,
      "address_data": <bindata of 0x33445566334455663344556633445566>
    }
  ],
  "canonical_name": <bindata of "www.example.com">,
  "answer_type": GETDNS_NAMETYPE_DNS,
  "intermediate_aliases": [],
  "replies_tree":
  [
    {     # This is the first reply
      "header": { "id": 23456, "qr": 1, "opcode": 0, ... },
      "question": { "qname": <bindata of "www.example.com">, "qtype": 1, "qclass": 1 },
      "answer":
      [
        {
          "name": <bindata of "www.example.com">,
          "type": 1,
          "class": 1,
          "ttl": 33000,
          "rdata":
          {
            "ipv4_address": <bindata of 0x0a0b0c01>
            "rdata_raw": <bindata of 0x0a0b0c01>
          }
        }
      ],
      "authority":
      [
        {
          "name": <bindata of "ns1.example.com">,
          "type": 1,
          "class": 1,
          "ttl": 600,
          "rdata":
          {
            "ipv4_address": <bindata of 0x65439876>
            "rdata_raw": <bindata of 0x65439876>
          }
        }
      ]
      "additional": [],
      "canonical_name": <bindata of "www.example.com">,
      "answer_type": GETDNS_NAMETYPE_DNS
    },
    {     # This is the second reply
      "header": { "id": 47809, "qr": 1, "opcode": 0, ... },
      "question": { "qname": <bindata of "www.example.com">, "qtype": 28, "qclass": 1 },
      "answer":
      [
        {
          "name": <bindata of "www.example.com">,
          "type": 28,
          "class": 1,
          "ttl": 1000,
          "rdata":
          {
            "ipv6_address": <bindata of 0x33445566334455663344556633445566>
            "rdata_raw": <bindata of 0x33445566334455663344556633445566>
          }
       }
      ],
      "authority": [  # Same as for other record... ]
      "additional": [],
    },
  ]
}

In DNS responses, domain names are treated special. RFC 1035 describes a form of name compression that requires that the entire record be available for analysis. The API deals with this by converting compressed names into full names when returning names in the replies_tree. This conversion happens for qname in question; name in the answer, authority, and additional; and in domain names in the data in names under rdata where the response type is AFSDB, CNAME, MX, NS, PTR, RP, RT, and SOA.

4.2 Converting Domain Names

Names in DNS fields are stored in a fashion very different from the normal presentation format normally used in applications. The DNS format is described in the first paragraph in Section 3.1 of RFC 1035; the presentation format here is a null-terminated string with interior dots. These helper functions only work with names in the DNS format that are not compressed. They are useful for converting domain names in the replies_tree to and from the FQDN presentation format.

getdns_convert_dns_name_to_fqdn() converts a domain name in DNS format to the presentation format. For example, the hex sequence 03 77 77 77 07 65 78 61 6d 70 6c 65 03 63 6f 6d 00 would be converted to "www.example.com". getdns_convert_fqdn_to_dns_name() does the reverse: it converts a null-terminated string in FQDN format to bytes in DNS format.

getdns_return_t getdns_convert_dns_name_to_fqdn( const getdns_bindata *dns_name_wire_fmt, char **fqdn_as_string ); getdns_return_t getdns_convert_fqdn_to_dns_name( const char *fqdn_as_string, getdns_bindata **dns_name_wire_fmt );

The returned values are allocated with the default system allocator, namely malloc. The caller is responsible of disposing these allocations with free.

5. Additional Definitions and Descriptions

5.1 A Few Needed Definitions

typedef struct getdns_context getdns_context; typedef uint64_t getdns_transaction_t; typedef enum getdns_data_type { t_dict, t_list, t_int, t_bindata } getdns_data_type; typedef struct getdns_bindata { size_t size; uint8_t *data; } getdns_bindata; typedef struct getdns_dict getdns_dict; typedef struct getdns_list getdns_list;

5.2 Return Codes

The return codes for all the functions are:

GETDNS_RETURN_GOOD

Good

GETDNS_RETURN_GENERIC_ERROR

Generic error

GETDNS_RETURN_BAD_DOMAIN_NAME

Badly-formed domain name in first argument

GETDNS_RETURN_BAD_CONTEXT

The context has internal deficiencies

GETDNS_RETURN_CONTEXT_UPDATE_FAIL

Did not update the context

GETDNS_RETURN_UNKNOWN_TRANSACTION

An attempt was made to cancel a callback with a transaction_id that is not recognized

GETDNS_RETURN_NO_SUCH_LIST_ITEM

A helper function for lists had an index argument that was too high.

GETDNS_RETURN_NO_SUCH_DICT_NAME

A helper function for dicts had a name argument that for a name that is not in the dict.

GETDNS_RETURN_WRONG_TYPE_REQUESTED

A helper function was supposed to return a certain type for an item, but the wrong type was given.

GETDNS_RETURN_NO_SUCH_EXTENSION

A name in the extensions dict is not a valid extension.

GETDNS_RETURN_EXTENSION_MISFORMAT

One or more of the extensions have a bad format.

GETDNS_RETURN_DNSSEC_WITH_STUB_DISALLOWED

A query was made with a context that is using stub resolution and a DNSSEC extension specified.

GETDNS_RETURN_MEMORY_ERROR

Unable to allocate the memory required.

GETDNS_RETURN_INVALID_PARAMETER

A required parameter had an invalid value.

GETDNS_RETURN_NOT_IMPLEMENTED

The library did not have the requested API feature implemented.

5.3 Types of RDATA Returned in the API

The names in the rdata dicts in replies are:

A (1)

ipv4_address (a bindata)

NS (2)

nsdname (a bindata)

MD (3)

madname (a bindata)

MF (4)

madname (a bindata)

CNAME (5)

cname (a bindata)

SOA (6)

mname (a bindata), rname (a bindata), serial (an int), refresh (an int), refresh (an int), retry (an int), and expire (an int)

MB (7)

madname (a bindata)

MG (8)

mgmname (a bindata)

MR (9)

newname (a bindata)

NULL (10)

anything (a bindata)

WKS (11)

address (a bindata), protocol (an int), and bitmap (a bindata)

PTR (12)

ptrdname (a bindata)

HINFO (13)

cpu (a bindata) and os (a bindata)

MINFO (14)

rmailbx (a bindata) and emailbx (a bindata)

MX (15)

preference (an int) and exchange (a bindata)

TXT (16)

txt_strings (a list) which contains zero or more bindata elements that are text strings

RP (17)

mbox_dname (a bindata) and txt_dname (a bindata)

AFSDB (18)

subtype (an int) and hostname (a bindata)

X25 (19)

psdn_address (a bindata)

ISDN (20)

isdn_address (a bindata) and sa (a bindata)

RT (21)

preference (an int) and intermediate_host (a bindata)

NSAP (22)

nsap (a bindata)

SIG (24)

sig_obsolete (a bindata)

KEY (25)

key_obsolete (a bindata)

PX (26)

preference (an int), map822 (a bindata), and mapx400 (a bindata)

GPOS (27)

longitude (a bindata), latitude (a bindata), and altitude (a bindata)

AAAA (28)

ipv6_address (a bindata)

LOC (29)

loc_obsolete (a bindata)

NXT (30)

nxt_obsolete (a bindata)

EID (31)

eid_unknown (a bindata)

NIMLOC (32)

nimloc_unknown (a bindata)

SRV (33)

priority (an int), weight (an int), port (an int), and target (a bindata)

ATMA (34)

format (an int) and address (a bindata)

NAPTR (35)

order (an int), preference (an int), flags (a bindata), service (a bindata), regexp (a bindata), and replacement (a bindata).

KX (36)

preference (an int) and exchanger (a bindata)

CERT (37)

type (an int), key_tag (an int), algorithm (an int), and certificate_or_crl (a bindata)

A6 (38)

a6_obsolete (a bindata)

DNAME (39)

target (a bindata)

SINK (40)

sink_unknown (a bindata)

OPT (41)

options (a list). Each element of the options list is a dict with two names: option_code (an int) and option_data (a bindata).

APL (42)

apitems (a list). Each element of the apitems list is a dict with four names: address_family (an int), prefix (an int), n (an int), and afdpart (a bindata)

DS (43)

key_tag (an int), algorithm (an int), digest_type (an int), and digest (a bindata)

SSHFP (44)

algorithm (an int), fp_type (an int), and fingerprint (a bindata)

IPSECKEY (45)

algorithm (an int), gateway_type (an int), precedence (an int), gateway, and public_key (a bindata)

RRSIG (46)

type_covered (an int), algorithm (an int), labels (an int), original_ttl (an int), signature_expiration (an int), signature_inception (an int), key_tag (an int), signers_name (a bindata), and signature (a bindata)

NSEC (47)

next_domain_name (a bindata) and type_bit_maps (a bindata)

DNSKEY (48)

flags (an int), protocol (an int), algorithm (an int), and public_key (a bindata)

DHCID (49)

dhcid_opaque (a bindata)

NSEC3 (50)

hash_algorithm (an int), flags (an int), iterations (an int), salt (a bindata), next_hashed_owner_name (a bindata), and type_bit_maps (a bindata)

NSEC3PARAM (51)

hash_algorithm (an int), flags (an int), iterations (an int), and salt (a bindata)

TLSA (52)

certificate_usage (an int), selector (an int), matching_type (an int), and certificate_association_data (a bindata).

HIP (55)

pk_algorithm (an int), hit (a bindata), public_key (a bindata), and rendezvous_servers (a list) with each element a bindata with the dname of the rendezvous_server.

NINFO (56)

ninfo_unknown (a bindata)

RKEY (57)

rkey_unknown (a bindata)

TALINK (58)

talink_unknown (a bindata)

CDS (59)

key_tag (an int), algorithm (an int), digest_type (an int), and digest (a bindata)

CDNSKEY (60)

flags (an int), protocol (an int), algorithm (an int), and public_key (a bindata)

OPENPGPKEY (61)

openpgpkey_unknown (a bindata)

CSYNC (62)

serial (an int), flags (an int), and type_bit_maps (a bindata)

SPF (99)

text (a bindata)

UINFO (100)

uinfo_unknown (a bindata)

UID (101)

uid_unknown (a bindata)

GID (102)

gid_unknown (a bindata)

UNSPEC (103)

unspec_unknown (a bindata)

NID (104)

preference (an int) and node_id (a bindata)

L32 (105)

preference (an int) and locator32 (a bindata)

L64 (106)

preference (an int) and locator64 (a bindata)

LP (107)

preference (an int) and fqdn (a bindata)

EUI48 (108)

eui48_address (a bindata)

EUI64 (109)

eui64_address (a bindata)

TKEY (249)

algorithm (a bindata), inception (an int), expiration (an int), mode (an int), error (an int), key_data (a bindata), and other_data (a bindata)

TSIG (250)

algorithm (a bindata), time_signed (a bindata), fudge (an int), mac (a bindata), original_id (an int), error (an int), and other_data (a bindata)

MAILB (253)

mailb-unknown (a bindata)

MAILA (254)

maila-unknown (a bindata)

URI (256)

priority (an int), weight (an int), and target (a bindata)

CAA (257)

flags (an int), tag (a bindata), and value (a bindata)

TA (32768)

ta_unknown (a bindata)

DLV (32769)

Identical to DS (43)

6. Examples

This section gives examples of code that calls the API to do many common tasks. The purpose of the code here is to give application developers a quick hands-on demo of using the API.

Note that the examples here all use getdns_libevent.h as the include that will call in the API code as well as calling in libevent as the event library. They also use getdns_context_set_libevent_base() as the name of the function to set the event base in the DNS context. If you are using a different event library, you will of course use a different #include at the beginning of your code, and a different name for the event base function.

6.1 Get Both IPv4 and IPv6 Addresses for a Domain Name Using Quick Results

This is an example of a common call to getdns_address().


#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <getdns_libevent.h>

/* Set up the callback function, which will also do the processing of the results */
void callback(getdns_context        *context,
              getdns_callback_type_t callback_type,
              getdns_dict           *response, 
              void                  *userarg,
              getdns_transaction_t   transaction_id)
{
    getdns_return_t r;  /* Holder for all function returns */
    uint32_t        status;
    getdns_bindata  *address_data;
    char            *first = NULL, *second = NULL;

    (void) context; /* unused parameter */

    printf( "Callback for query \"%s\" with request ID %"PRIu64".\n"
          , (char *)userarg, transaction_id );

    switch(callback_type) {
    case GETDNS_CALLBACK_CANCEL:
        printf("Transaction with ID %"PRIu64" was cancelled.\n", transaction_id);
        return;
    case GETDNS_CALLBACK_TIMEOUT:
        printf("Transaction with ID %"PRIu64" timed out.\n", transaction_id);
        return;
    case GETDNS_CALLBACK_ERROR:
        printf("An error occurred for transaction ID %"PRIu64".\n", transaction_id);
        return;
    default: break;
    }
    assert( callback_type == GETDNS_CALLBACK_COMPLETE );

    if ((r = getdns_dict_get_int(response, "status", &status)))
        fprintf(stderr, "Could not get \"status\" from response");

    else if (status != GETDNS_RESPSTATUS_GOOD)
        fprintf(stderr, "The search had no results, and a return value of %"PRIu32".\n", status);

    else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/0/address_data", &address_data)))
        fprintf(stderr, "Could not get first address");

    else if (!(first = getdns_display_ip_address(address_data)))
        fprintf(stderr, "Could not convert first address to string\n");

    else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/1/address_data", &address_data)))
        fprintf(stderr, "Could not get second address");

    else if (!(second = getdns_display_ip_address(address_data)))
        fprintf(stderr, "Could not convert second address to string\n");

    if (first) {
        printf("The address is %s\n", first);
        free(first);
    }
    if (second) {
        printf("The address is %s\n", second);
        free(second);
    }
    if (r) {
        assert( r != GETDNS_RETURN_GOOD );
        fprintf(stderr, ": %d\n", r);
    }
    getdns_dict_destroy(response); 
}

int main()
{
    getdns_return_t      r;  /* Holder for all function returns */
    getdns_context      *context    = NULL;
    struct event_base   *event_base = NULL;
    getdns_dict         *extensions = NULL;
    char                *query_name = "www.example.com";
    /* Could add things here to help identify this call */
    char                *userarg    = query_name;
    getdns_transaction_t transaction_id;

    if ((r = getdns_context_create(&context, 1)))
        fprintf(stderr, "Trying to create the context failed");

    else if (!(event_base = event_base_new()))
        fprintf(stderr, "Trying to create the event base failed.\n");

    else if ((r = getdns_extension_set_libevent_base(context, event_base)))
        fprintf(stderr, "Setting the event base failed");

    else if ((r = getdns_address( context, query_name, extensions
                                , userarg, &transaction_id, callback)))
        fprintf(stderr, "Error scheduling asynchronous request");

    else {
        printf("Request with transaction ID %"PRIu64" scheduled.\n", transaction_id);
        if (event_base_dispatch(event_base) < 0)
            fprintf(stderr, "Error dispatching events\n");
    }

    /* Clean up */
    if (event_base)
        event_base_free(event_base);

    if (context)
        getdns_context_destroy(context);

    /* Assuming we get here, leave gracefully */
    exit(EXIT_SUCCESS);
}

6.2 Get IPv4 and IPv6 Addresses for a Domain Name

This example is similar to the previous one, except that it retrieves more information than just the addresses, so it traverses the replies_tree. In this case, it gets both the addresses and their TTLs.


#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <getdns_libevent.h>

/* Set up the callback function, which will also do the processing of the results */
void callback(getdns_context        *context,
              getdns_callback_type_t callback_type,
              getdns_dict           *response, 
              void                  *userarg,
              getdns_transaction_t   transaction_id)
{
    getdns_return_t r;  /* Holder for all function returns */
    getdns_list    *replies_tree;
    size_t          n_replies, i;

    (void) context; (void) userarg; /* unused parameters */

    switch(callback_type) {
    case GETDNS_CALLBACK_CANCEL:
        printf("Transaction with ID %"PRIu64" was cancelled.\n", transaction_id);
        return;
    case GETDNS_CALLBACK_TIMEOUT:
        printf("Transaction with ID %"PRIu64" timed out.\n", transaction_id);
        return;
    case GETDNS_CALLBACK_ERROR:
        printf("An error occurred for transaction ID %"PRIu64".\n", transaction_id);
        return;
    default: break;
    }
    assert( callback_type == GETDNS_CALLBACK_COMPLETE );

    if ((r = getdns_dict_get_list(response, "replies_tree", &replies_tree)))
        fprintf(stderr, "Could not get \"replies_tree\" from response");

    else if ((r = getdns_list_get_length(replies_tree, &n_replies)))
        fprintf(stderr, "Could not get replies_tree\'s length");

    else for (i = 0; i < n_replies && r == GETDNS_RETURN_GOOD; i++) {
        getdns_dict *reply;
        getdns_list *answer;
        size_t       n_answers, j;

        if ((r = getdns_list_get_dict(replies_tree, i, &reply)))
            fprintf(stderr, "Could not get address %zu from just_address_answers", i);

        else if ((r = getdns_dict_get_list(reply, "answer", &answer)))
            fprintf(stderr, "Could not get \"address_data\" from address");

        else if ((r = getdns_list_get_length(answer, &n_answers)))
            fprintf(stderr, "Could not get answer section\'s length");

        else for (j = 0; j < n_answers && r == GETDNS_RETURN_GOOD; j++) {
            getdns_dict    *rr;
            getdns_bindata *address = NULL;

            if ((r = getdns_list_get_dict(answer, j, &rr)))
                fprintf(stderr, "Could net get rr %zu from answer section", j);

            else if (getdns_dict_get_bindata(rr, "/rdata/ipv4_address", &address) == GETDNS_RETURN_GOOD)
                printf("The IPv4 address is ");

            else if (getdns_dict_get_bindata(rr, "/rdata/ipv6_address", &address) == GETDNS_RETURN_GOOD)
                printf("The IPv6 address is ");

            if (address) {
                char *address_str;
                if (!(address_str = getdns_display_ip_address(address))) {
                    fprintf(stderr, "Could not convert second address to string");
                    r = GETDNS_RETURN_MEMORY_ERROR;
                    break;
                }
                printf("%s\n", address_str);
                free(address_str);
            }
        }
    }
    if (r) {
        assert( r != GETDNS_RETURN_GOOD );
        fprintf(stderr, ": %d\n", r);
    }
    getdns_dict_destroy(response); 
}

int main()
{
    getdns_return_t      r;  /* Holder for all function returns */
    getdns_context      *context    = NULL;
    struct event_base   *event_base = NULL;
    getdns_dict         *extensions = NULL;
    char                *query_name = "www.example.com";
    /* Could add things here to help identify this call */
    char                *userarg    = NULL;
    getdns_transaction_t transaction_id;

    if ((r = getdns_context_create(&context, 1)))
        fprintf(stderr, "Trying to create the context failed");

    else if (!(event_base = event_base_new()))
        fprintf(stderr, "Trying to create the event base failed.\n");

    else if ((r = getdns_extension_set_libevent_base(context, event_base)))
        fprintf(stderr, "Setting the event base failed");

    else if ((r = getdns_address( context, query_name, extensions
                                , userarg, &transaction_id, callback)))
        fprintf(stderr, "Error scheduling asynchronous request");

    else if (event_base_dispatch(event_base) < 0)
        fprintf(stderr, "Error dispatching events\n");

    /* Clean up */
    if (event_base)
        event_base_free(event_base);

    if (context)
        getdns_context_destroy(context);

    /* Assuming we get here, leave gracefully */
    exit(EXIT_SUCCESS);
}

6.3 Get Addresses for a Domain Name And Their Associated DNSSEC Validation Status

This example shows how to check for secure DNSSEC results using the dnssec_return_status extension. In the innermost loop of the callback function, add a check for the DNSSEC status. It shows how to add two extensions to the extensions argument of the call.

getdns_dict *extensions = getdns_dict_create();
r = getdns_dict_set_int(extensions, "return_both_v4_and_v6", GETDNS_EXTENSION_TRUE);
r = getdns_dict_set_int(extensions, "dnssec_return_status", GETDNS_EXTENSION_TRUE);
. . .
if (rr_type == GETDNS_RRTYPE_A) {
    uint32_t dnssec_status;
    r = getdns_dict_get_int(answer, "dnssec_status", &dnssec_status);
    if (dnssec_status != GETDNS_DNSSEC_SECURE) {
        // Log the DNSSEC status somewhere

    } else {
        // Deal with the record however you were going to
    }
}
. . .

You can put the DNSSEC status check outside the check for the particular type of record you care about, but you will then get log messages for bad status on records you might not care about as well.

6.4 Using the API Synchronously with getdns_general_sync()

This example is the same as the earlier examples, but uses getdns_general_sync() and thus does not use the async code. Note that the processing of the answers is essentially the same as it is for the synchronous example, it is just done in main().


#include <stdio.h>
#include <assert.h>
#include <getdns_core_only.h>

int main()
{
    getdns_return_t  r; /* Holder for all function returns */
    getdns_context  *context    = NULL;
    getdns_dict     *response   = NULL;
    getdns_dict     *extensions = NULL;
    getdns_bindata  *address_data;
    char            *first = NULL, *second = NULL;

    /* Create the DNS context for this call */
    if ((r = getdns_context_create(&context, 1)))
        fprintf(stderr, "Trying to create the context failed");

    else if (!(extensions = getdns_dict_create()))
        fprintf(stderr, "Could not create extensions dict.\n");

    else if ((r = getdns_dict_set_int(extensions, "return_both_v4_and_v6", GETDNS_EXTENSION_TRUE)))
        fprintf(stderr, "Trying to set an extension do both IPv4 and IPv6 failed");

    else if ((r = getdns_general_sync(context, "example.com", GETDNS_RRTYPE_A, extensions, &response)))
        fprintf(stderr, "Error scheduling synchronous request");
    
    else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/0/address_data", &address_data)))
        fprintf(stderr, "Could not get first address");

    else if (!(first = getdns_display_ip_address(address_data)))
        fprintf(stderr, "Could not convert first address to string\n");

    else if ((r = getdns_dict_get_bindata(response, "/just_address_answers/1/address_data", &address_data)))
        fprintf(stderr, "Could not get second address");

    else if (!(second = getdns_display_ip_address(address_data)))
        fprintf(stderr, "Could not convert second address to string\n");

    if (first) {
        printf("The address is %s\n", first);
        free(first);
    }
    if (second) {
        printf("The address is %s\n", second);
        free(second);
    }
    /* Clean up */
    if (response)
        getdns_dict_destroy(response); 

    if (extensions)
        getdns_dict_destroy(extensions);

    if (context)
        getdns_context_destroy(context);

    if (r) {
        assert( r != GETDNS_RETURN_GOOD );

        fprintf(stderr, ": %d\n", r);
        exit(EXIT_FAILURE);
    }
    /* Assuming we get here, leave gracefully */
    exit(EXIT_SUCCESS);
}

6.5 Getting Names from the Reverse Tree with getdns_hostname()

This example shows how to use getdns_hostname() to get names from the DNS reverse tree.


#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <getdns_libevent.h>

/* Set up the callback function, which will also do the processing of the results */
void callback(getdns_context        *context,
              getdns_callback_type_t callback_type,
              getdns_dict           *response, 
              void                  *userarg,
              getdns_transaction_t   transaction_id)
{
    getdns_return_t r;  /* Holder for all function returns */
    getdns_list    *answer;
    size_t          n_answers, i;

    (void) context; (void) userarg; /* unused parameters */

    switch(callback_type) {
    case GETDNS_CALLBACK_CANCEL:
        printf("Transaction with ID %"PRIu64" was cancelled.\n", transaction_id);
        return;
    case GETDNS_CALLBACK_TIMEOUT:
        printf("Transaction with ID %"PRIu64" timed out.\n", transaction_id);
        return;
    case GETDNS_CALLBACK_ERROR:
        printf("An error occurred for transaction ID %"PRIu64".\n", transaction_id);
        return;
    default: break;
    }
    assert( callback_type == GETDNS_CALLBACK_COMPLETE );

    if ((r = getdns_dict_get_list(response, "/replies_tree/0/answer", &answer)))
        fprintf(stderr, "Could not get \"answer\" section from first reply in the response");

    else if ((r = getdns_list_get_length(answer, &n_answers)))
        fprintf(stderr, "Could not get replies_tree\'s length");

    else for (i = 0; i < n_answers && r == GETDNS_RETURN_GOOD; i++) {
        getdns_dict    *rr;
        getdns_bindata *dname;
        char           *dname_str;

        if ((r = getdns_list_get_dict(answer, i, &rr)))
            fprintf(stderr, "Could not get rr %zu from answer section", i);

        else if (getdns_dict_get_bindata(rr, "/rdata/ptrdname", &dname))
            continue; /* Not a PTR */

        else if ((r = getdns_convert_dns_name_to_fqdn(dname, &dname_str)))
            fprintf(stderr, "Could not convert PTR dname to string");

        else {
            printf("The dname is %s\n", dname_str);
            free(dname_str);
        }
    }
    if (r) {
        assert( r != GETDNS_RETURN_GOOD );
        fprintf(stderr, ": %d\n", r);
    }
    getdns_dict_destroy(response); 
}

int main()
{
    getdns_return_t      r;  /* Holder for all function returns */
    getdns_context      *context      = NULL;
    struct event_base   *event_base   = NULL;
    getdns_bindata       address_type = { 4, (void *)"IPv4" };
    getdns_bindata       address_data = { 4, (void *)"\x08\x08\x08\x08" };
    getdns_dict         *address      = NULL;
    getdns_dict         *extensions   = NULL;
    /* Could add things here to help identify this call */
    char                *userarg      = NULL;
    getdns_transaction_t transaction_id;

    if ((r = getdns_context_create(&context, 1)))
        fprintf(stderr, "Trying to create the context failed");

    else if (!(event_base = event_base_new()))
        fprintf(stderr, "Trying to create the event base failed.\n");

    else if ((r = getdns_extension_set_libevent_base(context, event_base)))
        fprintf(stderr, "Setting the event base failed");

    else if (!(address = getdns_dict_create()))
        fprintf(stderr, "Could not create address dict.\n");

    else if ((r = getdns_dict_set_bindata(address, "address_type", &address_type)))
        fprintf(stderr, "Could not set address_type in address dict.\n");

    else if ((r = getdns_dict_set_bindata(address, "address_data", &address_data)))
        fprintf(stderr, "Could not set address_data in address dict.\n");

    else if ((r = getdns_hostname( context, address, extensions
                                 , userarg, &transaction_id, callback)))
        fprintf(stderr, "Error scheduling asynchronous request");

    else if (event_base_dispatch(event_base) < 0)
        fprintf(stderr, "Error dispatching events\n");

    /* Clean up */
    if (event_base)
        event_base_free(event_base);

    if (context)
        getdns_context_destroy(context);

    /* Assuming we get here, leave gracefully */
    exit(EXIT_SUCCESS);
}

7. More Helper Functions

The following two functions convert individual labels of IDNs between their Unicode encoding and their ASCII encoding. They follow the rules for IDNA 2008 described in RFC 5890-5892.

char * getdns_convert_ulabel_to_alabel( const char *ulabel );
char * getdns_convert_alabel_to_ulabel( const char *alabel );

If an application wants the API do perform DNSSEC validation without using the extensions, it can use the getdns_validate_dnssec() helper function.

getdns_return_t getdns_validate_dnssec( getdns_list *to_validate, getdns_list *bundle_of_support_records, getdns_list *trust_anchor_records );

The to_validate is a list of resource records being validated together with the associated signatures. The API will use the resource records in bundle_of_support_records to construct the validation chain and the DNSKEY or DS records in trust_anchor_records as trust anchors. The function returns one of GETDNS_DNSSEC_SECURE, GETDNS_DNSSEC_BOGUS, GETDNS_DNSSEC_INDETERMINATE, or GETDNS_DNSSEC_INSECURE.

The default list of trust anchor records that is used by the library to validate DNSSEC can be retrieved by using the getdns_root_trust_anchor helper function.

getdns_list * getdns_root_trust_anchor( time_t *utc_date_of_anchor );

When there are no default trust anchors NULL is returned. Upon successful return, the variable of type time_t, referenced by utc_date_of_anchor is set to the number of seconds since epoch the trust anchors were obtained.

There are two functions that help process data:

char * getdns_pretty_print_dict( const getdns_dict *some_dict );

This returns a string that is the nicely-formatted version of the dict and all of the named elements in it.

char * getdns_display_ip_address( const getdns_bindata *bindata_of_ipv4_or_ipv6_address );

This returns a string that is the nicely-formatted version of the IPv4 or IPv6 address in it. The API determines they type of address by the length given in the bindata.

All memory locations returned by these helper functions are allocated by the default system allocator, namely malloc. The caller is responsible of disposing these allocations with free.

8. DNS Contexts

Many calls in the DNS API require a DNS context. A DNS context contains the information that the API needs in order to process DNS calls, such as the locations of upstream DNS servers, DNSSEC trust anchors, and so on. The internal structure of the DNS context is opaque, and might be different on each OS. When a context is passed to any function, it must be an allocated context; the context must not be NULL.

A typical application using this API doesn't need to know anything about contexts. Basically, the application creates a default context, uses it in the functions that require a context, and then deallocates it when done. Context manipulation is available for more DNS-aware programs, but is unlikely to be of interest to applications that just want the results of lookups for A, AAAA, SRV, and PTR records.

It is expected that contexts in implementations of the API will not necessarily be thread-safe, but they will not be thread-hostile. A context should not be used by multiple threads: create a new context for use on a different thread. It is just fine for an application to have many contexts, and some DNS-heavy applications will certainly want to have many even if the application uses a single thread.

See above for the method for creating and destroying contexts. When the context is used in the API for the first time and set_from_os is 1, the API starts replacing some of the values with values from the OS, such as those that would be found in res_query(3), /etc/resolv.conf, and so on, then proceeds with the new function. Some advanced users will not want the API to change the values to the OS's defaults; if set_from_os is 0, the API will not do any updates to the initial values based on changes in the OS. For example, this might be useful if the API is acting as a stub resolver that is using a specific upstream recursive resolver chosen by the application, not the one that might come back from DHCP.

8.1 Updating the Context Automatically

The context returned by getdns_context_create() is updated by the API by default, such as when changes are made to /etc/resolv.conf. When there is a change, the callback function that is set in getdns_context_set_context_update_callback() (described below) is called.

Many of the defaults for a context come from the operating system under which the API is running. In specific, it is important that the implementation should try to replicate as best as possible the logic of a local getaddrinfo() when creating a new context. This includes making lookups in WINS for NetBIOS, mDNS lookups, nis names, and any other name lookup that getaddrinfo() normally does automatically. The API should look at nsswitch, the Windows resolver, and so on.

In the function definitions below, the choice listed in bold is the one used for the API default context.

8.2 Updating the Context Manually

Setting specific values in a context are done with value-specific functions shown here. The setting functions all return either GETDNS_RETURN_GOOD for success or GETDNS_RETURN_CONTEXT_UPDATE_FAIL for a failure to update the context.

An application can be notified when the context is changed.

getdns_return_t getdns_context_set_context_update_callback( getdns_context *context, void (*value)(getdns_context *context, getdns_context_code_t changed_item) );

The value is a pointer to the callback function that will be called when any context is changed. Such changes might be from automatic changes from the API (such as changes to /etc/resolv.conf), or might be from any of the API functions in this section being called. The second argument to the callback function specifies which of the context changed; the context codes are listed later in this document.

Calling getdns_context_set_context_update_callback with a second argument of NULL prevents updates to the context from causing callbacks.

8.3 Contexts for Basic Resolution

getdns_return_t getdns_context_set_resolution_type( getdns_context *context, getdns_resolution_t value );

Specifies whether DNS queries are performed with nonrecurive lookups or as a stub resolver. The value is GETDNS_RESOLUTION_RECURSING or GETDNS_RESOLUTION_STUB.

All implementations of this API can act as recursive resolvers, and that must be the default mode of the default context. Some implementations of this API are expected to also be able to act as stub resolvers. If an implementation of this API is only able to act as a recursive resolver, a call to getdns_context_set_resolution_type(somecontext, GETDNS_RESOLUTION_STUB) will return GETDNS_RETURN_CONTEXT_UPDATE_FAIL.

getdns_return_t getdns_context_set_namespaces( getdns_context *context, size_t namespace_count, getdns_namespace_t *namespaces );

The namespaces array contains an ordered list of namespaces that will be queried. Important: this context setting is ignored for the getdns_general and getdns_general_sync functions; it is used for the other funtions. The values are GETDNS_NAMESPACE_DNS, GETDNS_NAMESPACE_LOCALNAMES, GETDNS_NAMESPACE_NETBIOS, GETDNS_NAMESPACE_MDNS, and GETDNS_NAMESPACE_NIS. When a normal lookup is done, the API does the lookups in the order given and stops when it gets the first result; a different method with the same result would be to run the queries in parallel and return when it gets the first result. Because lookups might be done over different mechanisms because of the different namespaces, there can be information leakage that is similar to that seen with getaddrinfo(). The default is determined by the OS.

getdns_return_t getdns_context_set_dns_transport( getdns_context *context, getdns_transport_t value );

Specifies what transport is used for DNS lookups. The value is GETDNS_TRANSPORT_UDP_FIRST_AND_FALL_BACK_TO_TCP, GETDNS_TRANSPORT_UDP_ONLY, GETDNS_TRANSPORT_TCP_ONLY, or GETDNS_TRANSPORT_TCP_ONLY_KEEP_CONNECTIONS_OPEN.

getdns_return_t getdns_context_set_dns_transport_list( getdns_context *context, size_t transport_count, getdns_transport_list_t *transports );

The transports array contains an ordered list of transports that will be used for DNS lookups. If only one transport value is specified it will be the only transport used. Should it not be available basic resolution will fail. Fallback transport options are specified by including multiple values in the list. The values are GETDNS_TRANSPORT_UDP, GETDNS_TRANSPORT_TCP, or GETDNS_TRANSPORT_TLS. The default is a list containing GETDNS_TRANSPORT_UDP then GETDNS_TRANSPORT_TCP.

getdns_return_t getdns_context_set_idle_timeout( getdns_context *context, uint64_t timeout );

Specifies number of milliseconds the API will leave an idle TCP or TLS connection open for (idle means no outstanding responses and no pending queries). The default is 0.

getdns_return_t getdns_context_set_limit_outstanding_queries( getdns_context *context, uint16_t limit );

Specifies limit the number of outstanding DNS queries. The API will block itself from sending more queries if it is about to exceed this value, and instead keep those queries in an internal queue. The a value of 0 indicates that the number of outstanding DNS queries is unlimited.

getdns_return_t getdns_context_set_timeout( getdns_context *context, uint64_t timeout );

Specifies number of milliseconds the API will wait for request to return. The default is not specified.

8.4 Context for Recursive Resolvers

getdns_return_t getdns_context_set_follow_redirects( getdns_context *context, getdns_redirects_t value );

Specifies whether or not DNS queries follow redirects. The value is GETDNS_REDIRECTS_FOLLOW for normal following of redirects though CNAME and DNAME; or GETDNS_REDIRECTS_DO_NOT_FOLLOW to cause any lookups that would have gone through CNAME and DNAME to return the CNAME or DNAME, not the eventual target.

getdns_return_t getdns_context_set_dns_root_servers( getdns_context *context, getdns_list *addresses );

The list contains dicts that are addresses to be used for looking up top-level domains; the default is the list of "normal" IANA root servers. Each dict in the list contains at least two names: address_type (whose value is a bindata; it is currently either "IPv4" or "IPv6") and address_data (whose value is a bindata).

8.5 Context for Local Naming

getdns_return_t getdns_context_set_append_name( getdns_context *context, getdns_append_name_t value );

Specifies whether to append a suffix to the query string before the API starts resolving a name. The value is GETDNS_APPEND_NAME_ALWAYS, GETDNS_APPEND_NAME_ONLY_TO_SINGLE_LABEL_AFTER_FAILURE, GETDNS_APPEND_NAME_ONLY_TO_MULTIPLE_LABEL_NAME_AFTER_FAILURE, or GETDNS_APPEND_NAME_NEVER. This controls whether or not to append the suffix given by getdns_context_set_suffix

getdns_return_t getdns_context_set_suffix( getdns_context *context, getdns_list *value );

The value is a list of bindatas that are strings that are to be appended based on getdns_context_set_append_name; the default is an empty list. The values here follow the rules in section 2.1 of RFC 4343 to allow non-ASCII octets and special characters in labels.

8.6 Context for DNSSEC

These context settings affect queries that have extensions that specify the use of DNSSEC.

Applications that need to specify the DNSSEC trust anchors can use:

getdns_return_t getdns_context_set_dnssec_trust_anchors( getdns_context *context, getdns_list *value );

The value is a list of bindatas that are the DNSSEC trust anchors. The default is the trust anchors from the IANA root. The trust anchors are expressed as RDATAs from DNSKEY resource records.

In the rare case that an application needs to set the DNSSEC skew, it can:

getdns_return_t getdns_context_set_dnssec_allowed_skew( getdns_context *context, uint32_t value );

The value is the number of seconds of skew that is allowed in either direction when checking an RRSIG's Expiration and Inception fields. The default is 0.

8.7 Context Specific to Stub Resolvers

An application can change the quering mechanism of a context to be to act as a stub resolver. Such an application might first get the default information to make this change from the operating system, probably through DHCP.

Note that if a context is changed to being a stub resolver, this automatically prevents the application from using the extenstions for DNSSEC. An application that wants to both do DNSSEC and stub resolution must do its own DNSSEC processing, possibly with the getdns_validate_dnssec() function.

getdns_return_t getdns_context_set_upstream_recursive_servers( getdns_context *context, getdns_list *upstream_list );

The list of dicts define where a stub resolver will send queries. Each dict contains at least two names: address_type (whose value is a bindata; it is currently either "IPv4" or "IPv6") and address_data (whose value is a bindata). For IPv6 link-local addresses, a scope_id name (a bindata) can be provided. It might also contain port to specify which port to use to contact these DNS servers; the default is 53. If the stub and a recursive resolver both support TSIG (RFC 2845), the upstream_list entry can also contain tsig_algorithm (a bindata) that is the name of the TSIG hash algorithm, tsig_name (a bindata) that is the name of the TSIG key, and tsig_secret (a bindata) that is the TSIG key.

8.8 Context for EDNS

These context settings affect queries that have extensions that specify the use of OPT resource records. These come from RFC 6891.

getdns_return_t getdns_context_set_edns_maximum_udp_payload_size( getdns_context *context, uint16_t value );

The value is between 512 and 65535; when not set, outgoing values will adhere to the suggestions in RFC 6891 and may follow a scheme that uses multiple values to maximize receptivity.

getdns_return_t getdns_context_set_edns_extended_rcode( getdns_context *context, uint8_t value );

The value is between 0 and 255; the default is 0.

getdns_return_t getdns_context_set_edns_version( getdns_context *context, uint8_t value );

The value is between 0 and 255; the default is 0.

getdns_return_t getdns_context_set_edns_do_bit( getdns_context *context, uint8_t value );

The value is between 0 and 1; the default is 0.

8.9 Context Use of Custom Memory Management Functions

getdns_return_t getdns_context_set_memory_functions( getdns_context *context, void *(*malloc) (size_t), void *(*realloc) (void *, size_t), void (*free) (void *) );

The given memory management functions will be used for creating the response dicts. The response dicts inherit the custom memory management functions from the context and will deallocate themselves (and their members) with the custom deallocator. By default, the system malloc, realloc, and free are used.

getdns_return_t getdns_context_set_extended_memory_functions( getdns_context *context, void *userarg, void *(*malloc)(void *userarg, size_t sz), void *(*realloc)(void *userarg, void *ptr, size_t sz), void (*free)(void *userarg, void *ptr) );

The given extended memory management functions will be used for creating the response dicts. The value of userarg argument will be passed to the custom malloc, realloc, and free. The response dicts inherit the custom memory management functions and the value for userarg from the context and will deallocate themselves (and their members) with the custom deallocator.

8.10 Context Codes

The context codes for getdns_context_set_context_update_callback() are:

GETDNS_CONTEXT_CODE_NAMESPACES

Change related to getdns_context_set_namespaces

GETDNS_CONTEXT_CODE_RESOLUTION_TYPE

Change related to getdns_context_set_resolution_type

GETDNS_CONTEXT_CODE_FOLLOW_REDIRECTS

Change related to getdns_context_set_follow_redirects

GETDNS_CONTEXT_CODE_UPSTREAM_RECURSIVE_SERVERS

Change related to getdns_context_set_upstream_recursive_servers

GETDNS_CONTEXT_CODE_DNS_ROOT_SERVERS

Change related to getdns_context_set_dns_root_servers

GETDNS_CONTEXT_CODE_DNS_TRANSPORT

Change related to getdns_context_set_dns_transport

GETDNS_CONTEXT_CODE_LIMIT_OUTSTANDING_QUERIES

Change related to getdns_context_set_limit_outstanding_queries

GETDNS_CONTEXT_CODE_APPEND_NAME

Change related to getdns_context_set_append_name

GETDNS_CONTEXT_CODE_SUFFIX

Change related to getdns_context_set_suffix

GETDNS_CONTEXT_CODE_DNSSEC_TRUST_ANCHORS

Change related to getdns_context_set_dnssec_trust_anchors

GETDNS_CONTEXT_CODE_EDNS_MAXIMUM_UDP_PAYLOAD_SIZE

Change related to getdns_context_set_edns_maximum_udp_payload_size

GETDNS_CONTEXT_CODE_EDNS_EXTENDED_RCODE

Change related to getdns_context_set_edns_extended_rcode

GETDNS_CONTEXT_CODE_EDNS_VERSION

Change related to getdns_context_set_edns_version

GETDNS_CONTEXT_CODE_EDNS_DO_BIT

Change related to getdns_context_set_edns_do_bit

GETDNS_CONTEXT_CODE_DNSSEC_ALLOWED_SKEW

Change related to getdns_context_set_dnssec_allowed_skew

GETDNS_CONTEXT_CODE_MEMORY_FUNCTIONS

Change related to getdns_context_set_memory_functions

GETDNS_CONTEXT_CODE_TIMEOUT

Change related to getdns_context_set_timeout

GETDNS_CONTEXT_CODE_IDLE_TIMEOUT

Change related to getdns_context_set_idle_timeout

8.11 Getting API information and current Contexts

An application might want to see information about the API itself and inspect the current context. Use the getdns_context_get_api_information function.

getdns_dict * getdns_context_get_api_information( getdns_context *context );

The returned getdns_dict will contain the following name/value pairs:

  • version_string (a bindata) represents the version string for this version of the DNS API.
  • implementation_string (a bindata) is a string set by the API implementer. It might be human-readable, and it might have information in it useful to an application developer (but it doesn't have to).
  • resolution_type (an int) is the type of resolver that the API is acting as in this context: GETDNS_RESOLUTION_RECURSING or GETDNS_RESOLUTION_STUB (it will be a recursing resolver unless the application changed this in a context.
  • all_context (a dict) with names for all the types of context. This can be used with getdns_pretty_print_dict() for debugging.

9. The Generated Files

There is a tarball that includes the .h files, the examples, and so on. The examples all make, even though there is no API implementation, based on a pseudo-implementation in the tarball; see make-examples-PLATFORM.sh. Note that this currently builds fine on the Macintosh and Ubuntu; help is definitely appreciated on making the build process work on more platforms if it fails there.

10. Commentary

The following description of the API may be of value to those who might implement the design, and those who are using an implementation of the design.

10.1 API Design Considerations

The genesis of this DNS API design was seeing other DNS API designs flounder. There are other DNS APIs already available (such as draft-hayatnagarkar-dnsext-validator-api, as well as DNSSEC APIs in BIND and Unbound), but there has been very little uptake of them. In talking to application developers, there was a consistent story: that they felt that the APIs were developed by and for DNS people, not applications developers.

This API design comes from talking to a small handful of applications developers about what they would want to see in a modern DNS API. Now that the API is public, it would be great to hear from many more application developers about whether it would meet their needs if it was implemented. My goal is to create a design that is a natural follow-on to getaddrinfo() that has all the capabilities that most application developers might want now or in the next few years: access to all types of DNS records (including those which are yet to be defined), full DNSSEC awareness, IDN handling, and parity for IPv4 and IPv6 addresses.

Note that this is just a design for a new API: there is no implementation of the design yet, but at least one is being worked on. The process of designing the API without implementing it at the same time has the huge advantage that major design changes could be made without any worry about "but we already coded it the other way". In the early revisions of this document, many fundamental design choices changed over and over, and even bike-shedding-like changes were allowed because they didn't involve any programming effort.

This work was done independently, not through the IETF because the IETF generally doesn't take on API work, and has explicitly avoided DNS API work in the past.

This API design has a Creative Commons license so that it can be used widely by potential API implementers. This also allows other people who want to fork the design to do so cleanly. Of course, any implementation of this API can choose whatever kind of license the API implementer wishes, but it would be fabulous if one or more such implementations had Creative Commons or BSD-ish licenses.

The API relies heavily on C macros and hopefully has no magic numbers.

10.2 API Implementation Considerations

All implementations of this API must act as recursive resolvers, and some might choose not to be able to act as stub resolvers. Note that all implementations of this API must be DNSSEC validators.

Because there are many C event libraries available, and they have different calling routines, it is the implementation of an API that determines which event library is used. This is certainly not optimal for C programmers, but they appear to have gotten used to is so far. All implementations of this API must support synchronous calls with getdns_general_sync().

Versions are differentiated by version strings instead of version numbers. The version string for this API is "getdns April 2013". Each implementation is free to set the implementation string as it feels fit.

The API's .h file contains a macro called GETDNS_COMPILATION_COMMENT. This can be useful to an application which will use the API because it can check the string without calling any functions. Each time the API implementation is compiled, this string should be updated with unique information about the implementation build.

The implementation of both the async and sync getdns functions will copy all the values of the parameters into local memory, in case the application changes or deallocates them.


Creative
Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

getdns-1.5.1/AUTHORS0000644000175000017500000000041213416117763011001 00000000000000Craig Despeaux Neel Goyal Allison Mankin Melinda Shore Willem Toorop W.C.A. Wijngaards Glen Wiley getdns-1.5.1/COPYING0000644000175000017500000000271113416117763010770 00000000000000Copyright (c) 2013, Verisign, Inc., NLnet Labs All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the names of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. getdns-1.5.1/config.guess0000755000175000017500000012637313416117763012270 00000000000000#! /bin/sh # Attempt to guess a canonical system name. # Copyright 1992-2018 Free Software Foundation, Inc. timestamp='2018-02-24' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner; maintained since 2000 by Ben Elliston. # # You can get the latest version of this script from: # https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess # # Please send patches to . me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Options: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright 1992-2018 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > "$dummy.c" ; for c in cc gcc c89 c99 ; do if ($c -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case "$UNAME_SYSTEM" in Linux|GNU|GNU/*) # If the system lacks a compiler, then just pick glibc. # We could probably try harder. LIBC=gnu eval "$set_cc_for_build" cat <<-EOF > "$dummy.c" #include #if defined(__UCLIBC__) LIBC=uclibc #elif defined(__dietlibc__) LIBC=dietlibc #else LIBC=gnu #endif EOF eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`" # If ldd exists, use it to detect musl libc. if command -v ldd >/dev/null && \ ldd --version 2>&1 | grep -q ^musl then LIBC=musl fi ;; esac # Note: order is significant - the case branches are not exclusive. case "$UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ "/sbin/$sysctl" 2>/dev/null || \ "/usr/sbin/$sysctl" 2>/dev/null || \ echo unknown)` case "$UNAME_MACHINE_ARCH" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; earmv*) arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'` endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'` machine="${arch}${endian}"-unknown ;; *) machine="$UNAME_MACHINE_ARCH"-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently (or will in the future) and ABI. case "$UNAME_MACHINE_ARCH" in earm*) os=netbsdelf ;; arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval "$set_cc_for_build" if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # Determine ABI tags. case "$UNAME_MACHINE_ARCH" in earm*) expr='s/^earmv[0-9]/-eabi/;s/eb$//' abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"` ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "$UNAME_VERSION" in Debian*) release='-gnu' ;; *) release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "$machine-${os}${release}${abi}" exit ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` echo "$UNAME_MACHINE_ARCH"-unknown-bitrig"$UNAME_RELEASE" exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo "$UNAME_MACHINE_ARCH"-unknown-openbsd"$UNAME_RELEASE" exit ;; *:LibertyBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` echo "$UNAME_MACHINE_ARCH"-unknown-libertybsd"$UNAME_RELEASE" exit ;; *:MidnightBSD:*:*) echo "$UNAME_MACHINE"-unknown-midnightbsd"$UNAME_RELEASE" exit ;; *:ekkoBSD:*:*) echo "$UNAME_MACHINE"-unknown-ekkobsd"$UNAME_RELEASE" exit ;; *:SolidBSD:*:*) echo "$UNAME_MACHINE"-unknown-solidbsd"$UNAME_RELEASE" exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd"$UNAME_RELEASE" exit ;; *:MirBSD:*:*) echo "$UNAME_MACHINE"-unknown-mirbsd"$UNAME_RELEASE" exit ;; *:Sortix:*:*) echo "$UNAME_MACHINE"-unknown-sortix exit ;; *:Redox:*:*) echo "$UNAME_MACHINE"-unknown-redox exit ;; mips:OSF1:*.*) echo mips-dec-osf1 exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE=alpha ;; "EV4.5 (21064)") UNAME_MACHINE=alpha ;; "LCA4 (21066/21068)") UNAME_MACHINE=alpha ;; "EV5 (21164)") UNAME_MACHINE=alphaev5 ;; "EV5.6 (21164A)") UNAME_MACHINE=alphaev56 ;; "EV5.6 (21164PC)") UNAME_MACHINE=alphapca56 ;; "EV5.7 (21164PC)") UNAME_MACHINE=alphapca57 ;; "EV6 (21264)") UNAME_MACHINE=alphaev6 ;; "EV6.7 (21264A)") UNAME_MACHINE=alphaev67 ;; "EV6.8CB (21264C)") UNAME_MACHINE=alphaev68 ;; "EV6.8AL (21264B)") UNAME_MACHINE=alphaev68 ;; "EV6.8CX (21264D)") UNAME_MACHINE=alphaev68 ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE=alphaev69 ;; "EV7 (21364)") UNAME_MACHINE=alphaev7 ;; "EV7.9 (21364A)") UNAME_MACHINE=alphaev79 ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo "$UNAME_MACHINE"-dec-osf"`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`" # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo "$UNAME_MACHINE"-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo "$UNAME_MACHINE"-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix"$UNAME_RELEASE" exit ;; arm*:riscos:*:*|arm*:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo "$UNAME_MACHINE"-ibm-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`" exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`" exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux"$UNAME_RELEASE" exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval "$set_cc_for_build" SUN_ARCH=i386 # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH=x86_64 fi fi echo "$SUN_ARCH"-pc-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos"`echo "$UNAME_RELEASE"|sed -e 's/-/_/'`" exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos"$UNAME_RELEASE" exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos"$UNAME_RELEASE" ;; sun4) echo sparc-sun-sunos"$UNAME_RELEASE" ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos"$UNAME_RELEASE" exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint"$UNAME_RELEASE" exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint"$UNAME_RELEASE" exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint"$UNAME_RELEASE" exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint"$UNAME_RELEASE" exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint"$UNAME_RELEASE" exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint"$UNAME_RELEASE" exit ;; m68k:machten:*:*) echo m68k-apple-machten"$UNAME_RELEASE" exit ;; powerpc:machten:*:*) echo powerpc-apple-machten"$UNAME_RELEASE" exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix"$UNAME_RELEASE" exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix"$UNAME_RELEASE" exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix"$UNAME_RELEASE" exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval "$set_cc_for_build" sed 's/^ //' << EOF > "$dummy.c" #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" && dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`"$dummy" "$dummyarg"` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos"$UNAME_RELEASE" exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ "$UNAME_PROCESSOR" = mc88100 ] || [ "$UNAME_PROCESSOR" = mc88110 ] then if [ "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx ] || \ [ "$TARGET_BINARY_INTERFACE"x = x ] then echo m88k-dg-dgux"$UNAME_RELEASE" else echo m88k-dg-dguxbcs"$UNAME_RELEASE" fi else echo i586-dg-dgux"$UNAME_RELEASE" fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix"`echo "$UNAME_RELEASE"|sed -e 's/-/_/g'`" exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" fi echo "$UNAME_MACHINE"-ibm-aix"$IBM_REV" exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval "$set_cc_for_build" sed 's/^ //' << EOF > "$dummy.c" #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/lslpp ] ; then IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` else IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" fi echo "$IBM_ARCH"-ibm-aix"$IBM_REV" exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd"$UNAME_RELEASE" # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'` case "$UNAME_MACHINE" in 9000/31?) HP_ARCH=m68000 ;; 9000/[34]??) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "$sc_cpu_version" in 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "$sc_kernel_bits" in 32) HP_ARCH=hppa2.0n ;; 64) HP_ARCH=hppa2.0w ;; '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 esac ;; esac fi if [ "$HP_ARCH" = "" ]; then eval "$set_cc_for_build" sed 's/^ //' << EOF > "$dummy.c" #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ "$HP_ARCH" = hppa2.0w ] then eval "$set_cc_for_build" # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH=hppa2.0w else HP_ARCH=hppa64 fi fi echo "$HP_ARCH"-hp-hpux"$HPUX_REV" exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux"$HPUX_REV" exit ;; 3050*:HI-UX:*:*) eval "$set_cc_for_build" sed 's/^ //' << EOF > "$dummy.c" #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo "$UNAME_MACHINE"-unknown-osf1mk else echo "$UNAME_MACHINE"-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo "$UNAME_MACHINE"-pc-bsdi"$UNAME_RELEASE" exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi"$UNAME_RELEASE" exit ;; *:BSD/OS:*:*) echo "$UNAME_MACHINE"-unknown-bsdi"$UNAME_RELEASE" exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case "$UNAME_PROCESSOR" in amd64) UNAME_PROCESSOR=x86_64 ;; i386) UNAME_PROCESSOR=i586 ;; esac echo "$UNAME_PROCESSOR"-unknown-freebsd"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`" exit ;; i*:CYGWIN*:*) echo "$UNAME_MACHINE"-pc-cygwin exit ;; *:MINGW64*:*) echo "$UNAME_MACHINE"-pc-mingw64 exit ;; *:MINGW*:*) echo "$UNAME_MACHINE"-pc-mingw32 exit ;; *:MSYS*:*) echo "$UNAME_MACHINE"-pc-msys exit ;; i*:PW*:*) echo "$UNAME_MACHINE"-pc-pw32 exit ;; *:Interix*:*) case "$UNAME_MACHINE" in x86) echo i586-pc-interix"$UNAME_RELEASE" exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix"$UNAME_RELEASE" exit ;; IA64) echo ia64-unknown-interix"$UNAME_RELEASE" exit ;; esac ;; i*:UWIN*:*) echo "$UNAME_MACHINE"-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" exit ;; *:GNU:*:*) # the GNU system echo "`echo "$UNAME_MACHINE"|sed -e 's,[-/].*$,,'`-unknown-$LIBC`echo "$UNAME_RELEASE"|sed -e 's,/.*$,,'`" exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo "$UNAME_MACHINE-unknown-`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`-$LIBC" exit ;; i*86:Minix:*:*) echo "$UNAME_MACHINE"-pc-minix exit ;; aarch64:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC=gnulibc1 ; fi echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; arc:Linux:*:* | arceb:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; arm*:Linux:*:*) eval "$set_cc_for_build" if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabi else echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabihf fi fi exit ;; avr32*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; cris:Linux:*:*) echo "$UNAME_MACHINE"-axis-linux-"$LIBC" exit ;; crisv32:Linux:*:*) echo "$UNAME_MACHINE"-axis-linux-"$LIBC" exit ;; e2k:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; frv:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; hexagon:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; i*86:Linux:*:*) echo "$UNAME_MACHINE"-pc-linux-"$LIBC" exit ;; ia64:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; k1om:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; m32r*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; m68*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval "$set_cc_for_build" sed 's/^ //' << EOF > "$dummy.c" #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU'`" test "x$CPU" != x && { echo "$CPU-unknown-linux-$LIBC"; exit; } ;; mips64el:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; openrisc*:Linux:*:*) echo or1k-unknown-linux-"$LIBC" exit ;; or32:Linux:*:* | or1k*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; padre:Linux:*:*) echo sparc-unknown-linux-"$LIBC" exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-"$LIBC" exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-"$LIBC" ;; PA8*) echo hppa2.0-unknown-linux-"$LIBC" ;; *) echo hppa-unknown-linux-"$LIBC" ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-"$LIBC" exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-"$LIBC" exit ;; ppc64le:Linux:*:*) echo powerpc64le-unknown-linux-"$LIBC" exit ;; ppcle:Linux:*:*) echo powerpcle-unknown-linux-"$LIBC" exit ;; riscv32:Linux:*:* | riscv64:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo "$UNAME_MACHINE"-ibm-linux-"$LIBC" exit ;; sh64*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; sh*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; tile*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; vax:Linux:*:*) echo "$UNAME_MACHINE"-dec-linux-"$LIBC" exit ;; x86_64:Linux:*:*) if objdump -f /bin/sh | grep -q elf32-x86-64; then echo "$UNAME_MACHINE"-pc-linux-"$LIBC"x32 else echo "$UNAME_MACHINE"-pc-linux-"$LIBC" fi exit ;; xtensa*:Linux:*:*) echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo "$UNAME_MACHINE"-pc-sysv4.2uw"$UNAME_VERSION" exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo "$UNAME_MACHINE"-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo "$UNAME_MACHINE"-unknown-stop exit ;; i*86:atheos:*:*) echo "$UNAME_MACHINE"-unknown-atheos exit ;; i*86:syllable:*:*) echo "$UNAME_MACHINE"-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos"$UNAME_RELEASE" exit ;; i*86:*DOS:*:*) echo "$UNAME_MACHINE"-pc-msdosdjgpp exit ;; i*86:*:4.*:*) UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo "$UNAME_MACHINE"-univel-sysv"$UNAME_REL" else echo "$UNAME_MACHINE"-pc-sysv"$UNAME_REL" fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo "$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}{$UNAME_VERSION}" exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo "$UNAME_MACHINE"-pc-sco"$UNAME_REL" else echo "$UNAME_MACHINE"-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configure will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv"$UNAME_RELEASE" # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv"$UNAME_RELEASE" # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos"$UNAME_RELEASE" exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos"$UNAME_RELEASE" exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos"$UNAME_RELEASE" exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos"$UNAME_RELEASE" exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv"$UNAME_RELEASE" exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo "$UNAME_MACHINE"-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo "$UNAME_MACHINE"-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux"$UNAME_RELEASE" exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv"$UNAME_RELEASE" else echo mips-unknown-sysv"$UNAME_RELEASE" fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; x86_64:Haiku:*:*) echo x86_64-unknown-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux"$UNAME_RELEASE" exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux"$UNAME_RELEASE" exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux"$UNAME_RELEASE" exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux"$UNAME_RELEASE" exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux"$UNAME_RELEASE" exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux"$UNAME_RELEASE" exit ;; SX-ACE:SUPER-UX:*:*) echo sxace-nec-superux"$UNAME_RELEASE" exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody"$UNAME_RELEASE" exit ;; *:Rhapsody:*:*) echo "$UNAME_MACHINE"-apple-rhapsody"$UNAME_RELEASE" exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown eval "$set_cc_for_build" if test "$UNAME_PROCESSOR" = unknown ; then UNAME_PROCESSOR=powerpc fi if test "`echo "$UNAME_RELEASE" | sed -e 's/\..*//'`" -le 10 ; then if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_PPC >/dev/null then UNAME_PROCESSOR=powerpc fi fi elif test "$UNAME_PROCESSOR" = i386 ; then # Avoid executing cc on OS X 10.9, as it ships with a stub # that puts up a graphical alert prompting to install # developer tools. Any system running Mac OS X 10.7 or # later (Darwin 11 and later) is required to have a 64-bit # processor. This is not true of the ARM version of Darwin # that Apple uses in portable devices. UNAME_PROCESSOR=x86_64 fi echo "$UNAME_PROCESSOR"-apple-darwin"$UNAME_RELEASE" exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = x86; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo "$UNAME_PROCESSOR"-"$UNAME_MACHINE"-nto-qnx"$UNAME_RELEASE" exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-*:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk"$UNAME_RELEASE" exit ;; NSE-*:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk"$UNAME_RELEASE" exit ;; NSR-*:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk"$UNAME_RELEASE" exit ;; NSV-*:NONSTOP_KERNEL:*:*) echo nsv-tandem-nsk"$UNAME_RELEASE" exit ;; NSX-*:NONSTOP_KERNEL:*:*) echo nsx-tandem-nsk"$UNAME_RELEASE" exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo "$UNAME_MACHINE"-"$UNAME_SYSTEM"-"$UNAME_RELEASE" exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = 386; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo "$UNAME_MACHINE"-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux"$UNAME_RELEASE" exit ;; *:DragonFly:*:*) echo "$UNAME_MACHINE"-unknown-dragonfly"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`" exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "$UNAME_MACHINE" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo "$UNAME_MACHINE"-pc-skyos"`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'`" exit ;; i*86:rdos:*:*) echo "$UNAME_MACHINE"-pc-rdos exit ;; i*86:AROS:*:*) echo "$UNAME_MACHINE"-pc-aros exit ;; x86_64:VMkernel:*:*) echo "$UNAME_MACHINE"-unknown-esx exit ;; amd64:Isilon\ OneFS:*:*) echo x86_64-unknown-onefs exit ;; esac echo "$0: unable to guess system type" >&2 case "$UNAME_MACHINE:$UNAME_SYSTEM" in mips:Linux | mips64:Linux) # If we got here on MIPS GNU/Linux, output extra information. cat >&2 <&2 </dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = "$UNAME_MACHINE" UNAME_RELEASE = "$UNAME_RELEASE" UNAME_SYSTEM = "$UNAME_SYSTEM" UNAME_VERSION = "$UNAME_VERSION" EOF exit 1 # Local variables: # eval: (add-hook 'write-file-functions 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: getdns-1.5.1/Makefile.in0000644000175000017500000002601513416117763012005 00000000000000# # @configure_input@ # # # Copyright (c) 2013, Verisign, Inc., NLnet Labs # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the names of the copyright holders nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. package = @PACKAGE_NAME@ version = @PACKAGE_VERSION@@RELEASE_CANDIDATE@ tarname = @PACKAGE_TARNAME@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ distdir = $(tarname)-$(version) bintar = $(distdir)-bin.tar.gz prefix = @prefix@ datarootdir=@datarootdir@ exec_prefix = @exec_prefix@ bindir = @bindir@ docdir = @docdir@ libdir = @libdir@ srcdir = @srcdir@ INSTALL = @INSTALL@ all : default @GETDNS_QUERY@ @GETDNS_SERVER_MON@ everything: default cd src/test && $(MAKE) default: cd src && $(MAKE) $@ install-lib: cd src && $(MAKE) install install: getdns.pc getdns_ext_event.pc install-lib @INSTALL_GETDNS_QUERY@ @INSTALL_GETDNS_SERVER_MON@ $(INSTALL) -m 755 -d $(DESTDIR)$(docdir) $(INSTALL) -m 644 $(srcdir)/AUTHORS $(DESTDIR)$(docdir) $(INSTALL) -m 644 $(srcdir)/ChangeLog $(DESTDIR)$(docdir) $(INSTALL) -m 644 $(srcdir)/COPYING $(DESTDIR)$(docdir) $(INSTALL) -m 644 $(srcdir)/INSTALL $(DESTDIR)$(docdir) $(INSTALL) -m 644 $(srcdir)/LICENSE $(DESTDIR)$(docdir) $(INSTALL) -m 644 $(srcdir)/NEWS $(DESTDIR)$(docdir) $(INSTALL) -m 644 $(srcdir)/README.md $(DESTDIR)$(docdir) $(INSTALL) -m 755 -d $(DESTDIR)$(libdir)/pkgconfig $(INSTALL) -m 644 getdns.pc $(DESTDIR)$(libdir)/pkgconfig $(INSTALL) -m 644 getdns_ext_event.pc $(DESTDIR)$(libdir)/pkgconfig $(INSTALL) -m 755 -d $(DESTDIR)$(docdir)/spec $(INSTALL) -m 644 $(srcdir)/spec/index.html $(DESTDIR)$(docdir)/spec cd doc && $(MAKE) install @echo "***" @echo "*** !!! IMPORTANT !!!!" @echo "***" @echo "*** From release 1.2.0, getdns comes with built-in DNSSEC" @echo "*** trust anchor management. External trust anchor management," @echo "*** for example with unbound-anchor, is no longer necessary" @echo "*** and no longer recommended." @echo "***" @echo "*** Previously installed trust anchors, in the default location -" @echo "***" @echo "*** @TRUST_ANCHOR_FILE@" @echo "***" @echo "*** - will be preferred and used for DNSSEC validation, however" @echo "*** getdns will fallback to trust-anchors obtained via built-in" @echo "*** trust anchor management when the anchors from the default" @echo "*** location fail to validate the root DNSKEY rrset." @echo "***" @echo "*** To prevent expired DNSSEC trust anchors to be used for" @echo "*** validation, we strongly recommend removing the trust anchors" @echo "*** on the default location when there is no active external" @echo "*** trust anchor management keeping it up-to-date." @echo "***" uninstall: @UNINSTALL_GETDNS_QUERY@ @UNINSTALL_GETDNS_SERVER_MON@ rm -rf $(DESTDIR)$(docdir) cd doc && $(MAKE) $@ cd src && $(MAKE) $@ doc: FORCE cd doc && $(MAKE) $@ example: cd spec/example && $(MAKE) $@ test: default cd src/test && $(MAKE) $@ getdns_query: default cd src/tools && $(MAKE) $@ getdns_server_mon: default cd src/tools && $(MAKE) $@ stubby: cd src && $(MAKE) $@ scratchpad: default cd src/test && $(MAKE) $@ pad: scratchpad src/test/scratchpad || ./libtool exec gdb src/test/scratchpad install-getdns_query: install-lib cd src/tools && $(MAKE) $@ uninstall-getdns_query: cd src/tools && $(MAKE) $@ install-getdns_server_mon: install-lib @INSTALL_GETDNS_QUERY@ cd src/tools && $(MAKE) $@ uninstall-getdns_server_mon: cd src/tools && $(MAKE) $@ install-stubby: cd src && $(MAKE) $@ uninstall-stubby: cd src && $(MAKE) $@ clean: cd src && $(MAKE) $@ cd doc && $(MAKE) $@ cd spec/example && $(MAKE) $@ rm -f *.o *.pc depend: cd src && $(MAKE) $@ cd spec/example && $(MAKE) $@ distclean: cd src && $(MAKE) $@ rmdir src 2>/dev/null || true cd doc && $(MAKE) $@ rmdir doc 2>/dev/null || true cd spec/example && $(MAKE) $@ rmdir spec/example 2>/dev/null || true rmdir spec 2>/dev/null || true rm -f config.log config.status Makefile libtool getdns.pc getdns_ext_event.pc rm -fR autom4te.cache rm -f m4/libtool.m4 rm -f m4/lt~obsolete.m4 rm -f m4/ltoptions.m4 rm -f m4/ltsugar.m4 rm -f m4/ltversion.m4 rm -f $(distdir).tar.gz $(distdir).tar.gz.sha256 $(distdir).tar.gz.sha1 rm -f $(distdir).tar.gz.md5 $(distdir).tar.gz.asc megaclean: cd $(srcdir) && rm -fr * .dir-locals.el .gitignore .indent.pro .travis.yml && git reset --hard && git submodule update --init autoclean: megaclean libtoolize -ci autoreconf -fi dist: $(distdir).tar.gz pub: $(distdir).tar.gz.sha256 $(distdir).tar.gz.md5 $(distdir).tar.gz.asc $(distdir).tar.gz.sha1 $(distdir).tar.gz.sha256: $(distdir).tar.gz openssl sha256 $(distdir).tar.gz >$@ $(distdir).tar.gz.sha1: $(distdir).tar.gz openssl sha1 $(distdir).tar.gz >$@ $(distdir).tar.gz.md5: $(distdir).tar.gz openssl md5 $(distdir).tar.gz >$@ $(distdir).tar.gz.asc: $(distdir).tar.gz gpg --armor --detach-sig $(distdir).tar.gz bindist: $(bintar) $(bintar): $(distdir) chown -R 0:0 $(distdir) 2>/dev/null || true cd $(distdir); ./configure; make tar chof - $(distdir) | gzip -9 -c > $@ rm -rf $(distdir) $(distdir).tar.gz: $(distdir) chown -R 0:0 $(distdir) 2>/dev/null || true tar chof - $(distdir) | gzip -9 -c > $@ rm -rf $(distdir) $(distdir): mkdir -p $(distdir)/m4 mkdir -p $(distdir)/src mkdir -p $(distdir)/src/getdns mkdir -p $(distdir)/src/test mkdir -p $(distdir)/src/extension mkdir -p $(distdir)/src/compat mkdir -p $(distdir)/src/util mkdir -p $(distdir)/src/gldns mkdir -p $(distdir)/src/tools mkdir -p $(distdir)/src/jsmn mkdir -p $(distdir)/src/yxml mkdir -p $(distdir)/src/ssl_dane mkdir -p $(distdir)/doc mkdir -p $(distdir)/spec mkdir -p $(distdir)/spec/example mkdir -p $(distdir)/stubby mkdir -p $(distdir)/stubby/src mkdir -p $(distdir)/stubby/src/yaml mkdir -p $(distdir)/stubby/doc mkdir -p $(distdir)/stubby/systemd mkdir -p $(distdir)/stubby/contrib/upstart cp $(srcdir)/configure.ac $(distdir) cp $(srcdir)/configure $(distdir) cp $(srcdir)/AUTHORS $(distdir) cp $(srcdir)/ChangeLog $(distdir) cp $(srcdir)/COPYING $(distdir) cp $(srcdir)/INSTALL $(distdir) cp $(srcdir)/LICENSE $(distdir) cp $(srcdir)/NEWS $(distdir) cp $(srcdir)/README.md $(distdir) cp $(srcdir)/Makefile.in $(distdir) cp $(srcdir)/install-sh $(distdir) cp $(srcdir)/config.sub $(distdir) cp $(srcdir)/config.guess $(distdir) cp $(srcdir)/getdns.pc.in $(distdir) cp $(srcdir)/getdns_ext_event.pc.in $(distdir) cp libtool $(distdir) cp $(srcdir)/ltmain.sh $(distdir) cp $(srcdir)/m4/*.m4 $(distdir)/m4 cp $(srcdir)/src/*.in $(distdir)/src cp $(srcdir)/src/*.[ch] $(distdir)/src cp $(srcdir)/src/*.symbols $(distdir)/src cp $(srcdir)/src/extension/*.[ch] $(distdir)/src/extension cp $(srcdir)/src/extension/*.symbols $(distdir)/src/extension cp $(srcdir)/src/getdns/*.in $(distdir)/src/getdns cp $(srcdir)/src/getdns/getdns_*.h $(distdir)/src/getdns cp $(srcdir)/src/test/Makefile.in $(distdir)/src/test cp $(srcdir)/src/test/*.[ch] $(distdir)/src/test cp $(srcdir)/src/test/*.sh $(distdir)/src/test cp $(srcdir)/src/test/*.good $(distdir)/src/test cp $(srcdir)/src/compat/*.[ch] $(distdir)/src/compat cp $(srcdir)/src/util/*.[ch] $(distdir)/src/util cp -r $(srcdir)/src/util/orig-headers $(distdir)/src/util cp -r $(srcdir)/src/util/auxiliary $(distdir)/src/util cp $(srcdir)/src/gldns/*.[ch] $(distdir)/src/gldns cp $(srcdir)/doc/Makefile.in $(distdir)/doc cp $(srcdir)/doc/*.in $(distdir)/doc cp $(srcdir)/doc/manpgaltnames $(distdir)/doc cp $(srcdir)/spec/*.html $(distdir)/spec cp $(srcdir)/spec/example/Makefile.in $(distdir)/spec/example cp $(srcdir)/spec/example/*.[ch] $(distdir)/spec/example cp $(srcdir)/src/tools/Makefile.in $(distdir)/src/tools cp $(srcdir)/src/tools/*.[ch] $(distdir)/src/tools cp $(srcdir)/stubby/stubby.yml.example $(distdir)/stubby cp $(srcdir)/stubby/macos/stubby-setdns-macos.sh $(distdir)/stubby cp $(srcdir)/stubby/src/*.[ch] $(distdir)/stubby/src cp $(srcdir)/stubby/src/yaml/*.[ch] $(distdir)/stubby/src/yaml cp $(srcdir)/stubby/COPYING $(distdir)/stubby cp $(srcdir)/stubby/README.md $(distdir)/stubby cp $(srcdir)/stubby/doc/stubby.1.in $(distdir)/stubby/doc cp $(srcdir)/stubby/systemd/README.md $(distdir)/stubby/systemd cp $(srcdir)/stubby/systemd/stubby.conf $(distdir)/stubby/systemd cp $(srcdir)/stubby/systemd/stubby.service $(distdir)/stubby/systemd cp $(srcdir)/stubby/contrib/upstart/stubby.conf $(distdir)/stubby/contrib/upstart cp $(srcdir)/src/jsmn/*.[ch] $(distdir)/src/jsmn cp $(srcdir)/src/jsmn/LICENSE $(distdir)/src/jsmn cp $(srcdir)/src/jsmn/README.md $(distdir)/src/jsmn cp $(srcdir)/src/yxml/*.[ch] $(distdir)/src/yxml cp $(srcdir)/src/yxml/COPYING $(distdir)/src/yxml cp $(srcdir)/src/yxml/yxml.pod $(distdir)/src/yxml cp $(srcdir)/src/ssl_dane/danessl.[ch] $(distdir)/src/ssl_dane cp $(srcdir)/src/ssl_dane/README.md $(distdir)/src/ssl_dane rm -f $(distdir)/Makefile $(distdir)/src/Makefile $(distdir)/src/getdns/getdns.h $(distdir)/spec/example/Makefile $(distdir)/src/test/Makefile $(distdir)/doc/Makefile $(distdir)/src/config.h distcheck: $(distdir).tar.gz gzip -cd $(distdir).tar.gz | tar xvf - cd $(distdir) && ./configure cd $(distdir) && $(MAKE) all cd $(distdir) && $(MAKE) check cd $(distdir) && $(MAKE) DESTDIR=$${PWD}/_inst install cd $(distdir) && $(MAKE) DESTDIR=$${PWD}/_inst uninstall @remaining="`find $${PWD}/$(distdir)/_inst -type f | wc -l`"; \ if test "$${remaining}" -ne 0; then echo "@@@ $${remaining} file(s) remaining in stage directory!"; \ exit 1; \ fi cd $(distdir) && $(MAKE) clean rm -rf $(distdir) @echo "*** Package $(distdir).tar.gz is ready for distribution" getdns.pc: $(srcdir)/getdns.pc.in ./config.status $@ getdns_ext_event.pc: $(srcdir)/getdns_ext_event.pc.in ./config.status $@ Makefile: $(srcdir)/Makefile.in config.status ./config.status $@ configure.status: configure ./config.status --recheck .PHONY: all distclean clean default doc test FORCE: getdns-1.5.1/NEWS0000644000175000017500000000004313416117763010430 00000000000000this page intentionally left blank getdns-1.5.1/getdns.pc.in0000644000175000017500000000035113416117763012150 00000000000000prefix=@prefix@ exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: getdns Version: @GETDNS_VERSION@ Description: A modern asynchronous DNS library Libs: -L${libdir} -lgetdns Cflags: -I${includedir} getdns-1.5.1/ltmain.sh0000644000175000017500000120467713416117763011575 00000000000000#! /bin/sh ## DO NOT EDIT - This file generated from ./build-aux/ltmain.in ## by inline-source v2014-01-03.01 # libtool (GNU libtool) 2.4.6 # Provide generalized library-building support services. # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . PROGRAM=libtool PACKAGE=libtool VERSION="2.4.6 Debian-2.4.6-4" package_revision=2.4.6 ## ------ ## ## Usage. ## ## ------ ## # Run './libtool --help' for help with using this script from the # command line. ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # After configure completes, it has a better idea of some of the # shell tools we need than the defaults used by the functions shared # with bootstrap, so set those here where they can still be over- # ridden by the user, but otherwise take precedence. : ${AUTOCONF="autoconf"} : ${AUTOMAKE="automake"} ## -------------------------- ## ## Source external libraries. ## ## -------------------------- ## # Much of our low-level functionality needs to be sourced from external # libraries, which are installed to $pkgauxdir. # Set a version string for this script. scriptversion=2015-10-12.13; # UTC # General shell script boiler plate, and helper functions. # Written by Gary V. Vaughan, 2004 # Copyright (C) 2004-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # As a special exception to the GNU General Public License, if you distribute # this file as part of a program or library that is built using GNU Libtool, # you may include this file under the same distribution terms that you use # for the rest of that program. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # Evaluate this file near the top of your script to gain access to # the functions and variables defined here: # # . `echo "$0" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh # # If you need to override any of the default environment variable # settings, do that before evaluating this file. ## -------------------- ## ## Shell normalisation. ## ## -------------------- ## # Some shells need a little help to be as Bourne compatible as possible. # Before doing anything else, make sure all that help has been provided! DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac fi # NLS nuisances: We save the old values in case they are required later. _G_user_locale= _G_safe_locale= for _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test set = \"\${$_G_var+set}\"; then save_$_G_var=\$$_G_var $_G_var=C export $_G_var _G_user_locale=\"$_G_var=\\\$save_\$_G_var; \$_G_user_locale\" _G_safe_locale=\"$_G_var=C; \$_G_safe_locale\" fi" done # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Make sure IFS has a sensible default sp=' ' nl=' ' IFS="$sp $nl" # There are apparently some retarded systems that use ';' as a PATH separator! if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi ## ------------------------- ## ## Locate command utilities. ## ## ------------------------- ## # func_executable_p FILE # ---------------------- # Check that FILE is an executable regular file. func_executable_p () { test -f "$1" && test -x "$1" } # func_path_progs PROGS_LIST CHECK_FUNC [PATH] # -------------------------------------------- # Search for either a program that responds to --version with output # containing "GNU", or else returned by CHECK_FUNC otherwise, by # trying all the directories in PATH with each of the elements of # PROGS_LIST. # # CHECK_FUNC should accept the path to a candidate program, and # set $func_check_prog_result if it truncates its output less than # $_G_path_prog_max characters. func_path_progs () { _G_progs_list=$1 _G_check_func=$2 _G_PATH=${3-"$PATH"} _G_path_prog_max=0 _G_path_prog_found=false _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:} for _G_dir in $_G_PATH; do IFS=$_G_save_IFS test -z "$_G_dir" && _G_dir=. for _G_prog_name in $_G_progs_list; do for _exeext in '' .EXE; do _G_path_prog=$_G_dir/$_G_prog_name$_exeext func_executable_p "$_G_path_prog" || continue case `"$_G_path_prog" --version 2>&1` in *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;; *) $_G_check_func $_G_path_prog func_path_progs_result=$func_check_prog_result ;; esac $_G_path_prog_found && break 3 done done done IFS=$_G_save_IFS test -z "$func_path_progs_result" && { echo "no acceptable sed could be found in \$PATH" >&2 exit 1 } } # We want to be able to use the functions in this file before configure # has figured out where the best binaries are kept, which means we have # to search for them ourselves - except when the results are already set # where we skip the searches. # Unless the user overrides by setting SED, search the path for either GNU # sed, or the sed that truncates its output the least. test -z "$SED" && { _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for _G_i in 1 2 3 4 5 6 7; do _G_sed_script=$_G_sed_script$nl$_G_sed_script done echo "$_G_sed_script" 2>/dev/null | sed 99q >conftest.sed _G_sed_script= func_check_prog_sed () { _G_path_prog=$1 _G_count=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo '' >> conftest.nl "$_G_path_prog" -f conftest.sed conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "sed gsed" func_check_prog_sed $PATH:/usr/xpg4/bin rm -f conftest.sed SED=$func_path_progs_result } # Unless the user overrides by setting GREP, search the path for either GNU # grep, or the grep that truncates its output the least. test -z "$GREP" && { func_check_prog_grep () { _G_path_prog=$1 _G_count=0 _G_path_prog_max=0 printf 0123456789 >conftest.in while : do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo 'GREP' >> conftest.nl "$_G_path_prog" -e 'GREP$' -e '-(cannot match)-' conftest.out 2>/dev/null || break diff conftest.out conftest.nl >/dev/null 2>&1 || break _G_count=`expr $_G_count + 1` if test "$_G_count" -gt "$_G_path_prog_max"; then # Best one so far, save it but keep looking for a better one func_check_prog_result=$_G_path_prog _G_path_prog_max=$_G_count fi # 10*(2^10) chars as input seems more than enough test 10 -lt "$_G_count" && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out } func_path_progs "grep ggrep" func_check_prog_grep $PATH:/usr/xpg4/bin GREP=$func_path_progs_result } ## ------------------------------- ## ## User overridable command paths. ## ## ------------------------------- ## # All uppercase variable names are used for environment variables. These # variables can be overridden by the user before calling a script that # uses them if a suitable command of that name is not already available # in the command search PATH. : ${CP="cp -f"} : ${ECHO="printf %s\n"} : ${EGREP="$GREP -E"} : ${FGREP="$GREP -F"} : ${LN_S="ln -s"} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} ## -------------------- ## ## Useful sed snippets. ## ## -------------------- ## sed_dirname='s|/[^/]*$||' sed_basename='s|^.*/||' # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='s|\([`"$\\]\)|\\\1|g' # Same as above, but do not quote variable references. sed_double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s|[].[^$\\*\/]|\\&|g' # Sed substitution that converts a w32 file name or path # that contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-'\' parameter expansions in output of sed_double_quote_subst that # were '\'-ed in input to the same. If an odd number of '\' preceded a # '$' in input to sed_double_quote_subst, that '$' was protected from # expansion. Since each input '\' is now two '\'s, look for any number # of runs of four '\'s followed by two '\'s and then a '$'. '\' that '$'. _G_bs='\\' _G_bs2='\\\\' _G_bs4='\\\\\\\\' _G_dollar='\$' sed_double_backslash="\ s/$_G_bs4/&\\ /g s/^$_G_bs2$_G_dollar/$_G_bs&/ s/\\([^$_G_bs]\\)$_G_bs2$_G_dollar/\\1$_G_bs2$_G_bs$_G_dollar/g s/\n//g" ## ----------------- ## ## Global variables. ## ## ----------------- ## # Except for the global variables explicitly listed below, the following # functions in the '^func_' namespace, and the '^require_' namespace # variables initialised in the 'Resource management' section, sourcing # this file will not pollute your global namespace with anything # else. There's no portable way to scope variables in Bourne shell # though, so actually running these functions will sometimes place # results into a variable named after the function, and often use # temporary variables in the '^_G_' namespace. If you are careful to # avoid using those namespaces casually in your sourcing script, things # should continue to work as you expect. And, of course, you can freely # overwrite any of the functions or variables defined here before # calling anything to customize them. EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. # Allow overriding, eg assuming that you follow the convention of # putting '$debug_cmd' at the start of all your functions, you can get # bash to show function call trace with: # # debug_cmd='eval echo "${FUNCNAME[0]} $*" >&2' bash your-script-name debug_cmd=${debug_cmd-":"} exit_cmd=: # By convention, finish your script with: # # exit $exit_status # # so that you can set exit_status to non-zero if you want to indicate # something went wrong during execution without actually bailing out at # the point of failure. exit_status=$EXIT_SUCCESS # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath=$0 # The name of this program. progname=`$ECHO "$progpath" |$SED "$sed_basename"` # Make sure we have an absolute progpath for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=`$ECHO "$progpath" |$SED "$sed_dirname"` progdir=`cd "$progdir" && pwd` progpath=$progdir/$progname ;; *) _G_IFS=$IFS IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS=$_G_IFS test -x "$progdir/$progname" && break done IFS=$_G_IFS test -n "$progdir" || progdir=`pwd` progpath=$progdir/$progname ;; esac ## ----------------- ## ## Standard options. ## ## ----------------- ## # The following options affect the operation of the functions defined # below, and should be set appropriately depending on run-time para- # meters passed on the command line. opt_dry_run=false opt_quiet=false opt_verbose=false # Categories 'all' and 'none' are always available. Append any others # you will pass as the first argument to func_warning from your own # code. warning_categories= # By default, display warnings according to 'opt_warning_types'. Set # 'warning_func' to ':' to elide all warnings, or func_fatal_error to # treat the next displayed warning as a fatal error. warning_func=func_warn_and_continue # Set to 'all' to display all warnings, 'none' to suppress all # warnings, or a space delimited list of some subset of # 'warning_categories' to display only the listed warnings. opt_warning_types=all ## -------------------- ## ## Resource management. ## ## -------------------- ## # This section contains definitions for functions that each ensure a # particular resource (a file, or a non-empty configuration variable for # example) is available, and if appropriate to extract default values # from pertinent package files. Call them using their associated # 'require_*' variable to ensure that they are executed, at most, once. # # It's entirely deliberate that calling these functions can set # variables that don't obey the namespace limitations obeyed by the rest # of this file, in order that that they be as useful as possible to # callers. # require_term_colors # ------------------- # Allow display of bold text on terminals that support it. require_term_colors=func_require_term_colors func_require_term_colors () { $debug_cmd test -t 1 && { # COLORTERM and USE_ANSI_COLORS environment variables take # precedence, because most terminfo databases neglect to describe # whether color sequences are supported. test -n "${COLORTERM+set}" && : ${USE_ANSI_COLORS="1"} if test 1 = "$USE_ANSI_COLORS"; then # Standard ANSI escape sequences tc_reset='' tc_bold=''; tc_standout='' tc_red=''; tc_green='' tc_blue=''; tc_cyan='' else # Otherwise trust the terminfo database after all. test -n "`tput sgr0 2>/dev/null`" && { tc_reset=`tput sgr0` test -n "`tput bold 2>/dev/null`" && tc_bold=`tput bold` tc_standout=$tc_bold test -n "`tput smso 2>/dev/null`" && tc_standout=`tput smso` test -n "`tput setaf 1 2>/dev/null`" && tc_red=`tput setaf 1` test -n "`tput setaf 2 2>/dev/null`" && tc_green=`tput setaf 2` test -n "`tput setaf 4 2>/dev/null`" && tc_blue=`tput setaf 4` test -n "`tput setaf 5 2>/dev/null`" && tc_cyan=`tput setaf 5` } fi } require_term_colors=: } ## ----------------- ## ## Function library. ## ## ----------------- ## # This section contains a variety of useful functions to call in your # scripts. Take note of the portable wrappers for features provided by # some modern shells, which will fall back to slower equivalents on # less featureful shells. # func_append VAR VALUE # --------------------- # Append VALUE onto the existing contents of VAR. # We should try to minimise forks, especially on Windows where they are # unreasonably slow, so skip the feature probes when bash or zsh are # being used: if test set = "${BASH_VERSION+set}${ZSH_VERSION+set}"; then : ${_G_HAVE_ARITH_OP="yes"} : ${_G_HAVE_XSI_OPS="yes"} # The += operator was introduced in bash 3.1 case $BASH_VERSION in [12].* | 3.0 | 3.0*) ;; *) : ${_G_HAVE_PLUSEQ_OP="yes"} ;; esac fi # _G_HAVE_PLUSEQ_OP # Can be empty, in which case the shell is probed, "yes" if += is # useable or anything else if it does not work. test -z "$_G_HAVE_PLUSEQ_OP" \ && (eval 'x=a; x+=" b"; test "a b" = "$x"') 2>/dev/null \ && _G_HAVE_PLUSEQ_OP=yes if test yes = "$_G_HAVE_PLUSEQ_OP" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_append () { $debug_cmd eval "$1+=\$2" }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_append () { $debug_cmd eval "$1=\$$1\$2" } fi # func_append_quoted VAR VALUE # ---------------------------- # Quote VALUE and append to the end of shell variable VAR, separated # by a space. if test yes = "$_G_HAVE_PLUSEQ_OP"; then eval 'func_append_quoted () { $debug_cmd func_quote_arg pretty "$2" eval "$1+=\\ \$func_quote_arg_result" }' else func_append_quoted () { $debug_cmd func_quote_arg pretty "$2" eval "$1=\$$1\\ \$func_quote_arg_result" } fi # func_append_uniq VAR VALUE # -------------------------- # Append unique VALUE onto the existing contents of VAR, assuming # entries are delimited by the first character of VALUE. For example: # # func_append_uniq options " --another-option option-argument" # # will only append to $options if " --another-option option-argument " # is not already present somewhere in $options already (note spaces at # each end implied by leading space in second argument). func_append_uniq () { $debug_cmd eval _G_current_value='`$ECHO $'$1'`' _G_delim=`expr "$2" : '\(.\)'` case $_G_delim$_G_current_value$_G_delim in *"$2$_G_delim"*) ;; *) func_append "$@" ;; esac } # func_arith TERM... # ------------------ # Set func_arith_result to the result of evaluating TERMs. test -z "$_G_HAVE_ARITH_OP" \ && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \ && _G_HAVE_ARITH_OP=yes if test yes = "$_G_HAVE_ARITH_OP"; then eval 'func_arith () { $debug_cmd func_arith_result=$(( $* )) }' else func_arith () { $debug_cmd func_arith_result=`expr "$@"` } fi # func_basename FILE # ------------------ # Set func_basename_result to FILE with everything up to and including # the last / stripped. if test yes = "$_G_HAVE_XSI_OPS"; then # If this shell supports suffix pattern removal, then use it to avoid # forking. Hide the definitions single quotes in case the shell chokes # on unsupported syntax... _b='func_basename_result=${1##*/}' _d='case $1 in */*) func_dirname_result=${1%/*}$2 ;; * ) func_dirname_result=$3 ;; esac' else # ...otherwise fall back to using sed. _b='func_basename_result=`$ECHO "$1" |$SED "$sed_basename"`' _d='func_dirname_result=`$ECHO "$1" |$SED "$sed_dirname"` if test "X$func_dirname_result" = "X$1"; then func_dirname_result=$3 else func_append func_dirname_result "$2" fi' fi eval 'func_basename () { $debug_cmd '"$_b"' }' # func_dirname FILE APPEND NONDIR_REPLACEMENT # ------------------------------------------- # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. eval 'func_dirname () { $debug_cmd '"$_d"' }' # func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT # -------------------------------------------------------- # Perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # For efficiency, we do not delegate to the functions above but instead # duplicate the functionality here. eval 'func_dirname_and_basename () { $debug_cmd '"$_b"' '"$_d"' }' # func_echo ARG... # ---------------- # Echo program name prefixed message. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname: $_G_line" done IFS=$func_echo_IFS } # func_echo_all ARG... # -------------------- # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_echo_infix_1 INFIX ARG... # ------------------------------ # Echo program name, followed by INFIX on the first line, with any # additional lines not showing INFIX. func_echo_infix_1 () { $debug_cmd $require_term_colors _G_infix=$1; shift _G_indent=$_G_infix _G_prefix="$progname: $_G_infix: " _G_message=$* # Strip color escape sequences before counting printable length for _G_tc in "$tc_reset" "$tc_bold" "$tc_standout" "$tc_red" "$tc_green" "$tc_blue" "$tc_cyan" do test -n "$_G_tc" && { _G_esc_tc=`$ECHO "$_G_tc" | $SED "$sed_make_literal_regex"` _G_indent=`$ECHO "$_G_indent" | $SED "s|$_G_esc_tc||g"` } done _G_indent="$progname: "`echo "$_G_indent" | $SED 's|.| |g'`" " ## exclude from sc_prohibit_nested_quotes func_echo_infix_1_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_infix_1_IFS $ECHO "$_G_prefix$tc_bold$_G_line$tc_reset" >&2 _G_prefix=$_G_indent done IFS=$func_echo_infix_1_IFS } # func_error ARG... # ----------------- # Echo program name prefixed message to standard error. func_error () { $debug_cmd $require_term_colors func_echo_infix_1 " $tc_standout${tc_red}error$tc_reset" "$*" >&2 } # func_fatal_error ARG... # ----------------------- # Echo program name prefixed message to standard error, and exit. func_fatal_error () { $debug_cmd func_error "$*" exit $EXIT_FAILURE } # func_grep EXPRESSION FILENAME # ----------------------------- # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $debug_cmd $GREP "$1" "$2" >/dev/null 2>&1 } # func_len STRING # --------------- # Set func_len_result to the length of STRING. STRING may not # start with a hyphen. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_len () { $debug_cmd func_len_result=${#1} }' else func_len () { $debug_cmd func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` } fi # func_mkdir_p DIRECTORY-PATH # --------------------------- # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { $debug_cmd _G_directory_path=$1 _G_dir_list= if test -n "$_G_directory_path" && test : != "$opt_dry_run"; then # Protect directory names starting with '-' case $_G_directory_path in -*) _G_directory_path=./$_G_directory_path ;; esac # While some portion of DIR does not yet exist... while test ! -d "$_G_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. _G_dir_list=$_G_directory_path:$_G_dir_list # If the last portion added has no slash in it, the list is done case $_G_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop _G_directory_path=`$ECHO "$_G_directory_path" | $SED -e "$sed_dirname"` done _G_dir_list=`$ECHO "$_G_dir_list" | $SED 's|:*$||'` func_mkdir_p_IFS=$IFS; IFS=: for _G_dir in $_G_dir_list; do IFS=$func_mkdir_p_IFS # mkdir can fail with a 'File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$_G_dir" 2>/dev/null || : done IFS=$func_mkdir_p_IFS # Bail out if we (or some other process) failed to create a directory. test -d "$_G_directory_path" || \ func_fatal_error "Failed to create '$1'" fi } # func_mktempdir [BASENAME] # ------------------------- # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, BASENAME is the basename for that directory. func_mktempdir () { $debug_cmd _G_template=${TMPDIR-/tmp}/${1-$progname} if test : = "$opt_dry_run"; then # Return a directory name, but don't create it in dry-run mode _G_tmpdir=$_G_template-$$ else # If mktemp works, use that first and foremost _G_tmpdir=`mktemp -d "$_G_template-XXXXXXXX" 2>/dev/null` if test ! -d "$_G_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race _G_tmpdir=$_G_template-${RANDOM-0}$$ func_mktempdir_umask=`umask` umask 0077 $MKDIR "$_G_tmpdir" umask $func_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$_G_tmpdir" || \ func_fatal_error "cannot create temporary directory '$_G_tmpdir'" fi $ECHO "$_G_tmpdir" } # func_normal_abspath PATH # ------------------------ # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. func_normal_abspath () { $debug_cmd # These SED scripts presuppose an absolute path with a trailing slash. _G_pathcar='s|^/\([^/]*\).*$|\1|' _G_pathcdr='s|^/[^/]*||' _G_removedotparts=':dotsl s|/\./|/|g t dotsl s|/\.$|/|' _G_collapseslashes='s|/\{1,\}|/|g' _G_finalslash='s|/*$|/|' # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_removedotparts" -e "$_G_collapseslashes" -e "$_G_finalslash"` while :; do # Processed it all yet? if test / = "$func_normal_abspath_tpath"; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result"; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$_G_pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_append func_normal_abspath_result "/$func_normal_abspath_tcomponent" ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_notquiet ARG... # -------------------- # Echo program name prefixed message only when not in quiet mode. func_notquiet () { $debug_cmd $opt_quiet || func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_relative_path SRCDIR DSTDIR # -------------------------------- # Set func_relative_path_result to the relative path from SRCDIR to DSTDIR. func_relative_path () { $debug_cmd func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=$func_dirname_result if test -z "$func_relative_path_tlibdir"; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test -n "$func_stripname_result"; then func_append func_relative_path_result "/$func_stripname_result" fi # Normalisation. If bindir is libdir, return '.' else relative path. if test -n "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result" func_relative_path_result=$func_stripname_result fi test -n "$func_relative_path_result" || func_relative_path_result=. : } # func_quote_portable EVAL ARG # ---------------------------- # Internal function to portably implement func_quote_arg. Note that we still # keep attention to performance here so we as much as possible try to avoid # calling sed binary (so far O(N) complexity as long as func_append is O(1)). func_quote_portable () { $debug_cmd func_quote_portable_result=$2 # one-time-loop (easy break) while true do if $1; then func_quote_portable_result=`$ECHO "$2" | $SED \ -e "$sed_double_quote_subst" -e "$sed_double_backslash"` break fi # Quote for eval. case $func_quote_portable_result in *[\\\`\"\$]*) case $func_quote_portable_result in *[\[\*\?]*) func_quote_portable_result=`$ECHO "$func_quote_portable_result" | $SED "$sed_quote_subst"` break ;; esac func_quote_portable_old_IFS=$IFS for _G_char in '\' '`' '"' '$' do # STATE($1) PREV($2) SEPARATOR($3) set start "" "" func_quote_portable_result=dummy"$_G_char$func_quote_portable_result$_G_char"dummy IFS=$_G_char for _G_part in $func_quote_portable_result do case $1 in quote) func_append func_quote_portable_result "$3$2" set quote "$_G_part" "\\$_G_char" ;; start) set first "" "" func_quote_portable_result= ;; first) set quote "$_G_part" "" ;; esac done done IFS=$func_quote_portable_old_IFS ;; *) ;; esac break done func_quote_portable_unquoted_result=$func_quote_portable_result case $func_quote_portable_result in # double-quote args containing shell metacharacters to delay # word splitting, command substitution and variable expansion # for a subsequent eval. # many bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_portable_result=\"$func_quote_portable_result\" ;; esac } # func_quotefast_eval ARG # ----------------------- # Quote one ARG (internal). This is equivalent to 'func_quote_arg eval ARG', # but optimized for speed. Result is stored in $func_quotefast_eval. if test xyes = `(x=; printf -v x %q yes; echo x"$x") 2>/dev/null`; then func_quotefast_eval () { printf -v func_quotefast_eval_result %q "$1" } else func_quotefast_eval () { func_quote_portable false "$1" func_quotefast_eval_result=$func_quote_portable_result } fi # func_quote_arg MODEs ARG # ------------------------ # Quote one ARG to be evaled later. MODEs argument may contain zero ore more # specifiers listed below separated by ',' character. This function returns two # values: # i) func_quote_arg_result # double-quoted (when needed), suitable for a subsequent eval # ii) func_quote_arg_unquoted_result # has all characters that are still active within double # quotes backslashified. Available only if 'unquoted' is specified. # # Available modes: # ---------------- # 'eval' (default) # - escape shell special characters # 'expand' # - the same as 'eval'; but do not quote variable references # 'pretty' # - request aesthetic output, i.e. '"a b"' instead of 'a\ b'. This might # later used in func_quote to get output like: 'echo "a b"' instead of # 'echo a\ b'. This is slower than default on some shells. # 'unquoted' # - produce also $func_quote_arg_unquoted_result which does not contain # wrapping double-quotes. # # Examples for 'func_quote_arg pretty,unquoted string': # # string | *_result | *_unquoted_result # ------------+-----------------------+------------------- # " | \" | \" # a b | "a b" | a b # "a b" | "\"a b\"" | \"a b\" # * | "*" | * # z="${x-$y}" | "z=\"\${x-\$y}\"" | z=\"\${x-\$y}\" # # Examples for 'func_quote_arg pretty,unquoted,expand string': # # string | *_result | *_unquoted_result # --------------+---------------------+-------------------- # z="${x-$y}" | "z=\"${x-$y}\"" | z=\"${x-$y}\" func_quote_arg () { _G_quote_expand=false case ,$1, in *,expand,*) _G_quote_expand=: ;; esac case ,$1, in *,pretty,*|*,expand,*|*,unquoted,*) func_quote_portable $_G_quote_expand "$2" func_quote_arg_result=$func_quote_portable_result func_quote_arg_unquoted_result=$func_quote_portable_unquoted_result ;; *) # Faster quote-for-eval for some shells. func_quotefast_eval "$2" func_quote_arg_result=$func_quotefast_eval_result ;; esac } # func_quote MODEs ARGs... # ------------------------ # Quote all ARGs to be evaled later and join them into single command. See # func_quote_arg's description for more info. func_quote () { $debug_cmd _G_func_quote_mode=$1 ; shift func_quote_result= while test 0 -lt $#; do func_quote_arg "$_G_func_quote_mode" "$1" if test -n "$func_quote_result"; then func_append func_quote_result " $func_quote_arg_result" else func_append func_quote_result "$func_quote_arg_result" fi shift done } # func_stripname PREFIX SUFFIX NAME # --------------------------------- # strip PREFIX and SUFFIX from NAME, and store in func_stripname_result. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_stripname () { $debug_cmd # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary variable first. func_stripname_result=$3 func_stripname_result=${func_stripname_result#"$1"} func_stripname_result=${func_stripname_result%"$2"} }' else func_stripname () { $debug_cmd case $2 in .*) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%\\\\$2\$%%"`;; *) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%$2\$%%"`;; esac } fi # func_show_eval CMD [FAIL_EXP] # ----------------------------- # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} func_quote_arg pretty,expand "$_G_cmd" eval "func_notquiet $func_quote_arg_result" $opt_dry_run || { eval "$_G_cmd" _G_status=$? if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_show_eval_locale CMD [FAIL_EXP] # ------------------------------------ # Unless opt_quiet is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { $debug_cmd _G_cmd=$1 _G_fail_exp=${2-':'} $opt_quiet || { func_quote_arg expand,pretty "$_G_cmd" eval "func_echo $func_quote_arg_result" } $opt_dry_run || { eval "$_G_user_locale $_G_cmd" _G_status=$? eval "$_G_safe_locale" if test 0 -ne "$_G_status"; then eval "(exit $_G_status); $_G_fail_exp" fi } } # func_tr_sh # ---------- # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { $debug_cmd case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED -e 's/^\([0-9]\)/_\1/' -e 's/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_verbose ARG... # ------------------- # Echo program name prefixed message in verbose mode only. func_verbose () { $debug_cmd $opt_verbose && func_echo "$*" : } # func_warn_and_continue ARG... # ----------------------------- # Echo program name prefixed warning message to standard error. func_warn_and_continue () { $debug_cmd $require_term_colors func_echo_infix_1 "${tc_red}warning$tc_reset" "$*" >&2 } # func_warning CATEGORY ARG... # ---------------------------- # Echo program name prefixed warning message to standard error. Warning # messages can be filtered according to CATEGORY, where this function # elides messages where CATEGORY is not listed in the global variable # 'opt_warning_types'. func_warning () { $debug_cmd # CATEGORY must be in the warning_categories list! case " $warning_categories " in *" $1 "*) ;; *) func_internal_error "invalid warning category '$1'" ;; esac _G_category=$1 shift case " $opt_warning_types " in *" $_G_category "*) $warning_func ${1+"$@"} ;; esac } # func_sort_ver VER1 VER2 # ----------------------- # 'sort -V' is not generally available. # Note this deviates from the version comparison in automake # in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a # but this should suffice as we won't be specifying old # version formats or redundant trailing .0 in bootstrap.conf. # If we did want full compatibility then we should probably # use m4_version_compare from autoconf. func_sort_ver () { $debug_cmd printf '%s\n%s\n' "$1" "$2" \ | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n } # func_lt_ver PREV CURR # --------------------- # Return true if PREV and CURR are in the correct order according to # func_sort_ver, otherwise false. Use it like this: # # func_lt_ver "$prev_ver" "$proposed_ver" || func_fatal_error "..." func_lt_ver () { $debug_cmd test "x$1" = x`func_sort_ver "$1" "$2" | $SED 1q` } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: #! /bin/sh # Set a version string for this script. scriptversion=2015-10-12.13; # UTC # A portable, pluggable option parser for Bourne shell. # Written by Gary V. Vaughan, 2010 # Copyright (C) 2010-2015 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program 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 General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Please report bugs or propose patches to gary@gnu.org. ## ------ ## ## Usage. ## ## ------ ## # This file is a library for parsing options in your shell scripts along # with assorted other useful supporting features that you can make use # of too. # # For the simplest scripts you might need only: # # #!/bin/sh # . relative/path/to/funclib.sh # . relative/path/to/options-parser # scriptversion=1.0 # func_options ${1+"$@"} # eval set dummy "$func_options_result"; shift # ...rest of your script... # # In order for the '--version' option to work, you will need to have a # suitably formatted comment like the one at the top of this file # starting with '# Written by ' and ending with '# warranty; '. # # For '-h' and '--help' to work, you will also need a one line # description of your script's purpose in a comment directly above the # '# Written by ' line, like the one at the top of this file. # # The default options also support '--debug', which will turn on shell # execution tracing (see the comment above debug_cmd below for another # use), and '--verbose' and the func_verbose function to allow your script # to display verbose messages only when your user has specified # '--verbose'. # # After sourcing this file, you can plug processing for additional # options by amending the variables from the 'Configuration' section # below, and following the instructions in the 'Option parsing' # section further down. ## -------------- ## ## Configuration. ## ## -------------- ## # You should override these variables in your script after sourcing this # file so that they reflect the customisations you have added to the # option parser. # The usage line for option parsing errors and the start of '-h' and # '--help' output messages. You can embed shell variables for delayed # expansion at the time the message is displayed, but you will need to # quote other shell meta-characters carefully to prevent them being # expanded when the contents are evaled. usage='$progpath [OPTION]...' # Short help message in response to '-h' and '--help'. Add to this or # override it after sourcing this library to reflect the full set of # options your script accepts. usage_message="\ --debug enable verbose shell tracing -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -v, --verbose verbosely report processing --version print version information and exit -h, --help print short or long help message and exit " # Additional text appended to 'usage_message' in response to '--help'. long_help_message=" Warning categories include: 'all' show all warnings 'none' turn off all the warnings 'error' warnings are treated as fatal errors" # Help message printed before fatal option parsing errors. fatal_help="Try '\$progname --help' for more information." ## ------------------------- ## ## Hook function management. ## ## ------------------------- ## # This section contains functions for adding, removing, and running hooks # to the main code. A hook is just a named list of of function, that can # be run in order later on. # func_hookable FUNC_NAME # ----------------------- # Declare that FUNC_NAME will run hooks added with # 'func_add_hook FUNC_NAME ...'. func_hookable () { $debug_cmd func_append hookable_fns " $1" } # func_add_hook FUNC_NAME HOOK_FUNC # --------------------------------- # Request that FUNC_NAME call HOOK_FUNC before it returns. FUNC_NAME must # first have been declared "hookable" by a call to 'func_hookable'. func_add_hook () { $debug_cmd case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not accept hook functions." ;; esac eval func_append ${1}_hooks '" $2"' } # func_remove_hook FUNC_NAME HOOK_FUNC # ------------------------------------ # Remove HOOK_FUNC from the list of functions called by FUNC_NAME. func_remove_hook () { $debug_cmd eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`' } # func_run_hooks FUNC_NAME [ARG]... # --------------------------------- # Run all hook functions registered to FUNC_NAME. # It is assumed that the list of hook functions contains nothing more # than a whitespace-delimited list of legal shell function names, and # no effort is wasted trying to catch shell meta-characters or preserve # whitespace. func_run_hooks () { $debug_cmd _G_rc_run_hooks=false case " $hookable_fns " in *" $1 "*) ;; *) func_fatal_error "'$1' does not support hook funcions.n" ;; esac eval _G_hook_fns=\$$1_hooks; shift for _G_hook in $_G_hook_fns; do if eval $_G_hook '"$@"'; then # store returned options list back into positional # parameters for next 'cmd' execution. eval _G_hook_result=\$${_G_hook}_result eval set dummy "$_G_hook_result"; shift _G_rc_run_hooks=: fi done $_G_rc_run_hooks && func_run_hooks_result=$_G_hook_result } ## --------------- ## ## Option parsing. ## ## --------------- ## # In order to add your own option parsing hooks, you must accept the # full positional parameter list in your hook function, you may remove/edit # any options that you action, and then pass back the remaining unprocessed # options in '_result', escaped suitably for # 'eval'. In this case you also must return $EXIT_SUCCESS to let the # hook's caller know that it should pay attention to # '_result'. Returning $EXIT_FAILURE signalizes that # arguments are left untouched by the hook and therefore caller will ignore the # result variable. # # Like this: # # my_options_prep () # { # $debug_cmd # # # Extend the existing usage message. # usage_message=$usage_message' # -s, --silent don'\''t print informational messages # ' # # No change in '$@' (ignored completely by this hook). There is # # no need to do the equivalent (but slower) action: # # func_quote eval ${1+"$@"} # # my_options_prep_result=$func_quote_result # false # } # func_add_hook func_options_prep my_options_prep # # # my_silent_option () # { # $debug_cmd # # args_changed=false # # # Note that for efficiency, we parse as many options as we can # # recognise in a loop before passing the remainder back to the # # caller on the first unrecognised argument we encounter. # while test $# -gt 0; do # opt=$1; shift # case $opt in # --silent|-s) opt_silent=: # args_changed=: # ;; # # Separate non-argument short options: # -s*) func_split_short_opt "$_G_opt" # set dummy "$func_split_short_opt_name" \ # "-$func_split_short_opt_arg" ${1+"$@"} # shift # args_changed=: # ;; # *) # Make sure the first unrecognised option "$_G_opt" # # is added back to "$@", we could need that later # # if $args_changed is true. # set dummy "$_G_opt" ${1+"$@"}; shift; break ;; # esac # done # # if $args_changed; then # func_quote eval ${1+"$@"} # my_silent_option_result=$func_quote_result # fi # # $args_changed # } # func_add_hook func_parse_options my_silent_option # # # my_option_validation () # { # $debug_cmd # # $opt_silent && $opt_verbose && func_fatal_help "\ # '--silent' and '--verbose' options are mutually exclusive." # # false # } # func_add_hook func_validate_options my_option_validation # # You'll also need to manually amend $usage_message to reflect the extra # options you parse. It's preferable to append if you can, so that # multiple option parsing hooks can be added safely. # func_options_finish [ARG]... # ---------------------------- # Finishing the option parse loop (call 'func_options' hooks ATM). func_options_finish () { $debug_cmd _G_func_options_finish_exit=false if func_run_hooks func_options ${1+"$@"}; then func_options_finish_result=$func_run_hooks_result _G_func_options_finish_exit=: fi $_G_func_options_finish_exit } # func_options [ARG]... # --------------------- # All the functions called inside func_options are hookable. See the # individual implementations for details. func_hookable func_options func_options () { $debug_cmd _G_rc_options=false for my_func in options_prep parse_options validate_options options_finish do if eval func_$my_func '${1+"$@"}'; then eval _G_res_var='$'"func_${my_func}_result" eval set dummy "$_G_res_var" ; shift _G_rc_options=: fi done # Save modified positional parameters for caller. As a top-level # options-parser function we always need to set the 'func_options_result' # variable (regardless the $_G_rc_options value). if $_G_rc_options; then func_options_result=$_G_res_var else func_quote eval ${1+"$@"} func_options_result=$func_quote_result fi $_G_rc_options } # func_options_prep [ARG]... # -------------------------- # All initialisations required before starting the option parse loop. # Note that when calling hook functions, we pass through the list of # positional parameters. If a hook function modifies that list, and # needs to propagate that back to rest of this script, then the complete # modified list must be put in 'func_run_hooks_result' before # returning $EXIT_SUCCESS (otherwise $EXIT_FAILURE is returned). func_hookable func_options_prep func_options_prep () { $debug_cmd # Option defaults: opt_verbose=false opt_warning_types= _G_rc_options_prep=false if func_run_hooks func_options_prep ${1+"$@"}; then _G_rc_options_prep=: # save modified positional parameters for caller func_options_prep_result=$func_run_hooks_result fi $_G_rc_options_prep } # func_parse_options [ARG]... # --------------------------- # The main option parsing loop. func_hookable func_parse_options func_parse_options () { $debug_cmd func_parse_options_result= _G_rc_parse_options=false # this just eases exit handling while test $# -gt 0; do # Defer to hook functions for initial option parsing, so they # get priority in the event of reusing an option name. if func_run_hooks func_parse_options ${1+"$@"}; then eval set dummy "$func_run_hooks_result"; shift _G_rc_parse_options=: fi # Break out of the loop if we already parsed every option. test $# -gt 0 || break _G_match_parse_options=: _G_opt=$1 shift case $_G_opt in --debug|-x) debug_cmd='set -x' func_echo "enabling shell trace mode" $debug_cmd ;; --no-warnings|--no-warning|--no-warn) set dummy --warnings none ${1+"$@"} shift ;; --warnings|--warning|-W) if test $# = 0 && func_missing_arg $_G_opt; then _G_rc_parse_options=: break fi case " $warning_categories $1" in *" $1 "*) # trailing space prevents matching last $1 above func_append_uniq opt_warning_types " $1" ;; *all) opt_warning_types=$warning_categories ;; *none) opt_warning_types=none warning_func=: ;; *error) opt_warning_types=$warning_categories warning_func=func_fatal_error ;; *) func_fatal_error \ "unsupported warning category: '$1'" ;; esac shift ;; --verbose|-v) opt_verbose=: ;; --version) func_version ;; -\?|-h) func_usage ;; --help) func_help ;; # Separate optargs to long options (plugins may need this): --*=*) func_split_equals "$_G_opt" set dummy "$func_split_equals_lhs" \ "$func_split_equals_rhs" ${1+"$@"} shift ;; # Separate optargs to short options: -W*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "$func_split_short_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-v*|-x*) func_split_short_opt "$_G_opt" set dummy "$func_split_short_opt_name" \ "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) _G_rc_parse_options=: ; break ;; -*) func_fatal_help "unrecognised option: '$_G_opt'" ;; *) set dummy "$_G_opt" ${1+"$@"}; shift _G_match_parse_options=false break ;; esac $_G_match_parse_options && _G_rc_parse_options=: done if $_G_rc_parse_options; then # save modified positional parameters for caller func_quote eval ${1+"$@"} func_parse_options_result=$func_quote_result fi $_G_rc_parse_options } # func_validate_options [ARG]... # ------------------------------ # Perform any sanity checks on option settings and/or unconsumed # arguments. func_hookable func_validate_options func_validate_options () { $debug_cmd _G_rc_validate_options=false # Display all warnings if -W was not given. test -n "$opt_warning_types" || opt_warning_types=" $warning_categories" if func_run_hooks func_validate_options ${1+"$@"}; then # save modified positional parameters for caller func_validate_options_result=$func_run_hooks_result _G_rc_validate_options=: fi # Bail if the options were screwed! $exit_cmd $EXIT_FAILURE $_G_rc_validate_options } ## ----------------- ## ## Helper functions. ## ## ----------------- ## # This section contains the helper functions used by the rest of the # hookable option parser framework in ascii-betical order. # func_fatal_help ARG... # ---------------------- # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { $debug_cmd eval \$ECHO \""Usage: $usage"\" eval \$ECHO \""$fatal_help"\" func_error ${1+"$@"} exit $EXIT_FAILURE } # func_help # --------- # Echo long help message to standard output and exit. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message" exit 0 } # func_missing_arg ARGNAME # ------------------------ # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $debug_cmd func_error "Missing argument for '$1'." exit_cmd=exit } # func_split_equals STRING # ------------------------ # Set func_split_equals_lhs and func_split_equals_rhs shell variables after # splitting STRING at the '=' sign. test -z "$_G_HAVE_XSI_OPS" \ && (eval 'x=a/b/c; test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \ && _G_HAVE_XSI_OPS=yes if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_equals () { $debug_cmd func_split_equals_lhs=${1%%=*} func_split_equals_rhs=${1#*=} test "x$func_split_equals_lhs" = "x$1" \ && func_split_equals_rhs= }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_equals () { $debug_cmd func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'` func_split_equals_rhs= test "x$func_split_equals_lhs" = "x$1" \ || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'` } fi #func_split_equals # func_split_short_opt SHORTOPT # ----------------------------- # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. if test yes = "$_G_HAVE_XSI_OPS" then # This is an XSI compatible shell, allowing a faster implementation... eval 'func_split_short_opt () { $debug_cmd func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"} }' else # ...otherwise fall back to using expr, which is often a shell builtin. func_split_short_opt () { $debug_cmd func_split_short_opt_name=`expr "x$1" : 'x-\(.\)'` func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'` } fi #func_split_short_opt # func_usage # ---------- # Echo short help message to standard output and exit. func_usage () { $debug_cmd func_usage_message $ECHO "Run '$progname --help |${PAGER-more}' for full usage" exit 0 } # func_usage_message # ------------------ # Echo short help message to standard output. func_usage_message () { $debug_cmd eval \$ECHO \""Usage: $usage"\" echo $SED -n 's|^# || /^Written by/{ x;p;x } h /^Written by/q' < "$progpath" echo eval \$ECHO \""$usage_message"\" } # func_version # ------------ # Echo version message to standard output and exit. func_version () { $debug_cmd printf '%s\n' "$progname $scriptversion" $SED -n ' /(C)/!b go :more /\./!{ N s|\n# | | b more } :go /^# Written by /,/# warranty; / { s|^# || s|^# *$|| s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2| p } /^# Written by / { s|^# || p } /^warranty; /q' < "$progpath" exit $? } # Local variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'before-save-hook 'time-stamp) # time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC" # time-stamp-time-zone: "UTC" # End: # Set a version string. scriptversion='(GNU libtool) 2.4.6' # func_echo ARG... # ---------------- # Libtool also displays the current mode in messages, so override # funclib.sh func_echo with this custom definition. func_echo () { $debug_cmd _G_message=$* func_echo_IFS=$IFS IFS=$nl for _G_line in $_G_message; do IFS=$func_echo_IFS $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line" done IFS=$func_echo_IFS } # func_warning ARG... # ------------------- # Libtool warnings are not categorized, so override funclib.sh # func_warning with this simpler definition. func_warning () { $debug_cmd $warning_func ${1+"$@"} } ## ---------------- ## ## Options parsing. ## ## ---------------- ## # Hook in the functions to make sure our own options are parsed during # the option parsing loop. usage='$progpath [OPTION]... [MODE-ARG]...' # Short help message in response to '-h'. usage_message="Options: --config show all configuration variables --debug enable verbose shell tracing -n, --dry-run display commands without modifying any files --features display basic configuration information and exit --mode=MODE use operation mode MODE --no-warnings equivalent to '-Wnone' --preserve-dup-deps don't remove duplicate dependency libraries --quiet, --silent don't print informational messages --tag=TAG use configuration variables from tag TAG -v, --verbose print more informational messages than default --version print version information -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] -h, --help, --help-all print short, long, or detailed help message " # Additional text appended to 'usage_message' in response to '--help'. func_help () { $debug_cmd func_usage_message $ECHO "$long_help_message MODE must be one of the following: clean remove files from the build directory compile compile a source file into a libtool object execute automatically set library path, then run a program finish complete the installation of libtool libraries install install libraries or executables link create a library or an executable uninstall remove libraries from an installed directory MODE-ARGS vary depending on the MODE. When passed as first option, '--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that. Try '$progname --help --mode=MODE' for a more detailed description of MODE. When reporting a bug, please describe a test case to reproduce it and include the following information: host-triplet: $host shell: $SHELL compiler: $LTCC compiler flags: $LTCFLAGS linker: $LD (gnu? $with_gnu_ld) version: $progname $scriptversion Debian-2.4.6-4 automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` Report bugs to . GNU libtool home page: . General help using GNU software: ." exit 0 } # func_lo2o OBJECT-NAME # --------------------- # Transform OBJECT-NAME from a '.lo' suffix to the platform specific # object suffix. lo2o=s/\\.lo\$/.$objext/ o2lo=s/\\.$objext\$/.lo/ if test yes = "$_G_HAVE_XSI_OPS"; then eval 'func_lo2o () { case $1 in *.lo) func_lo2o_result=${1%.lo}.$objext ;; * ) func_lo2o_result=$1 ;; esac }' # func_xform LIBOBJ-OR-SOURCE # --------------------------- # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise) # suffix to a '.lo' libtool-object suffix. eval 'func_xform () { func_xform_result=${1%.*}.lo }' else # ...otherwise fall back to using sed. func_lo2o () { func_lo2o_result=`$ECHO "$1" | $SED "$lo2o"` } func_xform () { func_xform_result=`$ECHO "$1" | $SED 's|\.[^.]*$|.lo|'` } fi # func_fatal_configuration ARG... # ------------------------------- # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func__fatal_error ${1+"$@"} \ "See the $PACKAGE documentation for more information." \ "Fatal configuration error." } # func_config # ----------- # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # ------------- # Display the features supported by this script. func_features () { echo "host: $host" if test yes = "$build_libtool_libs"; then echo "enable shared libraries" else echo "disable shared libraries" fi if test yes = "$build_old_libs"; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag TAGNAME # ----------------------- # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname=$1 re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf=/$re_begincf/,/$re_endcf/p # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # ------------------------ # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # libtool_options_prep [ARG]... # ----------------------------- # Preparation for options parsed by libtool. libtool_options_prep () { $debug_mode # Option defaults: opt_config=false opt_dlopen= opt_dry_run=false opt_help=false opt_mode= opt_preserve_dup_deps=false opt_quiet=false nonopt= preserve_args= _G_rc_lt_options_prep=: # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; *) _G_rc_lt_options_prep=false ;; esac if $_G_rc_lt_options_prep; then # Pass back the list of options. func_quote eval ${1+"$@"} libtool_options_prep_result=$func_quote_result fi $_G_rc_lt_options_prep } func_add_hook func_options_prep libtool_options_prep # libtool_parse_options [ARG]... # --------------------------------- # Provide handling for libtool specific options. libtool_parse_options () { $debug_cmd _G_rc_lt_parse_options=false # Perform our own loop to consume as many options as possible in # each iteration. while test $# -gt 0; do _G_match_lt_parse_options=: _G_opt=$1 shift case $_G_opt in --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) func_config ;; --dlopen|-dlopen) opt_dlopen="${opt_dlopen+$opt_dlopen }$1" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) func_features ;; --finish) set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $_G_opt && break opt_mode=$1 case $1 in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $_G_opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_quiet=false func_append preserve_args " $_G_opt" ;; --no-warnings|--no-warning|--no-warn) opt_warning=false func_append preserve_args " $_G_opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $_G_opt" ;; --silent|--quiet) opt_quiet=: opt_verbose=false func_append preserve_args " $_G_opt" ;; --tag) test $# = 0 && func_missing_arg $_G_opt && break opt_tag=$1 func_append preserve_args " $_G_opt $1" func_enable_tag "$1" shift ;; --verbose|-v) opt_quiet=false opt_verbose=: func_append preserve_args " $_G_opt" ;; # An option not handled by this hook function: *) set dummy "$_G_opt" ${1+"$@"} ; shift _G_match_lt_parse_options=false break ;; esac $_G_match_lt_parse_options && _G_rc_lt_parse_options=: done if $_G_rc_lt_parse_options; then # save modified positional parameters for caller func_quote eval ${1+"$@"} libtool_parse_options_result=$func_quote_result fi $_G_rc_lt_parse_options } func_add_hook func_parse_options libtool_parse_options # libtool_validate_options [ARG]... # --------------------------------- # Perform any sanity checks on option settings and/or unconsumed # arguments. libtool_validate_options () { # save first non-option argument if test 0 -lt $#; then nonopt=$1 shift fi # preserve --debug test : = "$debug_cmd" || func_append preserve_args " --debug" case $host in # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452 # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788 *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match test yes != "$build_libtool_libs" \ && test yes != "$build_old_libs" \ && func_fatal_configuration "not configured to build any kind of library" # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test execute != "$opt_mode"; then func_error "unrecognized option '-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help=$help help="Try '$progname --help --mode=$opt_mode' for more information." } # Pass back the unparsed argument list func_quote eval ${1+"$@"} libtool_validate_options_result=$func_quote_result } func_add_hook func_validate_options libtool_validate_options # Process options as early as possible so that --help and --version # can return quickly. func_options ${1+"$@"} eval set dummy "$func_options_result"; shift ## ----------- ## ## Main. ## ## ----------- ## magic='%%%MAGIC variable%%%' magic_exe='%%%MAGIC EXE variable%%%' # Global variables. extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # func_generated_by_libtool # True iff stdin has been generated by Libtool. This function is only # a basic sanity check; it will hardly flush out determined imposters. func_generated_by_libtool_p () { $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null | func_generated_by_libtool_p } # func_lalib_unsafe_p file # True iff FILE is a libtool '.la' library or '.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if 'file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case $lalib_p_line in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test yes = "$lalib_p" } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { test -f "$1" && $lt_truncate_bin < "$1" 2>/dev/null | func_generated_by_libtool_p } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $debug_cmd save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # 'FILE.' does not work on cygwin managed mounts. func_source () { $debug_cmd case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case $lt_sysroot:$1 in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result='='$func_stripname_result ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $debug_cmd if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with '--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=$1 if test yes = "$build_libtool_libs"; then write_lobj=\'$2\' else write_lobj=none fi if test yes = "$build_old_libs"; then write_oldobj=\'$3\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "$func_convert_core_file_wine_to_w32_tmp"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $debug_cmd # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result= if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result"; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $debug_cmd if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $debug_cmd # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $debug_cmd if test -z "$2" && test -n "$1"; then func_error "Could not determine host file name corresponding to" func_error " '$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result=$1 fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $debug_cmd if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " '$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result=$3 fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $debug_cmd case $4 in $1 ) func_to_host_path_result=$3$func_to_host_path_result ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via '$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $debug_cmd $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $debug_cmd case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result=$1 } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result=$func_convert_core_msys_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result=$func_convert_core_file_wine_to_w32_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $debug_cmd func_to_host_file_result=$1 if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result=$func_cygpath_result fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via '$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $debug_cmd if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd=func_convert_path_$func_stripname_result fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $debug_cmd func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result=$1 } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_msys_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result=$func_convert_core_path_wine_to_w32_result func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $debug_cmd func_to_host_path_result=$1 if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result=$func_cygpath_result func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_dll_def_p FILE # True iff FILE is a Windows DLL '.def' file. # Keep in sync with _LT_DLL_DEF_P in libtool.m4 func_dll_def_p () { $debug_cmd func_dll_def_p_tmp=`$SED -n \ -e 's/^[ ]*//' \ -e '/^\(;.*\)*$/d' \ -e 's/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p' \ -e q \ "$1"` test DEF = "$func_dll_def_p_tmp" } # func_mode_compile arg... func_mode_compile () { $debug_cmd # Get the compilation command and the source file. base_compile= srcfile=$nonopt # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg=$arg arg_mode=normal ;; target ) libobj=$arg arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify '-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs=$IFS; IFS=, for arg in $args; do IFS=$save_ifs func_append_quoted lastarg "$arg" done IFS=$save_ifs func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg=$srcfile srcfile=$arg ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with '-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj=$func_basename_result } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from '$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test yes = "$build_libtool_libs" \ || func_fatal_configuration "cannot build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_arg pretty "$libobj" test "X$libobj" != "X$func_quote_arg_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name '$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname=$func_basename_result xdir=$func_dirname_result lobj=$xdir$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test yes = "$build_old_libs"; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test no = "$pic_mode" && test pass_all != "$deplibs_check_method"; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test no = "$compiler_c_o"; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.$objext lockfile=$output_obj.lock else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test yes = "$need_locks"; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test warn = "$need_locks"; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_arg pretty "$srcfile" qsrcfile=$func_quote_arg_result # Only build a PIC object if we are building libtool libraries. if test yes = "$build_libtool_libs"; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test no != "$pic_mode"; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test yes = "$suppress_opt"; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test yes = "$build_old_libs"; then if test yes != "$pic_mode"; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test yes = "$compiler_c_o"; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test warn = "$need_locks" && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support '-c' and '-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test no != "$need_locks"; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test compile = "$opt_mode" && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a '.o' file suitable for static linking -static only build a '.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a 'standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix '.c' with the library object suffix, '.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to '-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the '--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the 'install' or 'cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE '-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE use a list of object files found in FILE to specify objects -os2dllname NAME force a short DLL name on OS/2 (no effect on other OSes) -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with '-') are ignored. Every other argument is treated as a filename. Files ending in '.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in '.la', then a libtool library is created, only library objects ('.lo' files) may be specified, and '-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created using 'ar' and 'ranlib', or on Windows using 'lib'. If OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically '/bin/rm'). RM-OPTIONS are options (such as '-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode '$opt_mode'" ;; esac echo $ECHO "Try '$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test : = "$opt_help"; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | $SED -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | $SED '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $debug_cmd # The first argument is the command name. cmd=$nonopt test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "'$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "'$file' was not linked with '-export-dynamic'" continue fi func_dirname "$file" "" "." dir=$func_dirname_result if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find '$dlname' in '$dir' or '$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir=$func_dirname_result ;; *) func_warning "'-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir=$absdir # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic=$magic # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file=$progdir/$program elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file=$progdir/$program fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if $opt_dry_run; then # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS else if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd=\$cmd$args fi } test execute = "$opt_mode" && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $debug_cmd libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "'$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument '$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and '=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do $SED -e "$sysroot_cmd s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_quiet && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the '-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the '$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the '$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the '$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to '/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test finish = "$opt_mode" && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $debug_cmd # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$SHELL" = "$nonopt" || test /bin/sh = "$nonopt" || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac then # Aesthetically quote it. func_quote_arg pretty "$nonopt" install_prog="$func_quote_arg_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_arg pretty "$arg" func_append install_prog "$func_quote_arg_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=false stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=: ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test X-m = "X$prev" && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_arg pretty "$arg" func_append install_prog " $func_quote_arg_result" if test -n "$arg2"; then func_quote_arg pretty "$arg2" fi func_append install_shared_prog " $func_quote_arg_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the '$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_arg pretty "$install_override_mode" func_append install_shared_prog " -m $func_quote_arg_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=: if $isdir; then destdir=$dest destname= else func_dirname_and_basename "$dest" "" "." destdir=$func_dirname_result destname=$func_basename_result # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "'$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "'$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "'$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir=$func_dirname_result func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install '$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking '$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname=$1 shift srcname=$realname test -n "$relink_command" && srcname=${realname}T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme=$stripme case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme= ;; esac ;; os2*) case $realname in *_dll.a) tstripme= ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try 'ln -sf' first, because the 'ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib=$destdir/$realname func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name=$func_basename_result instname=$dir/${name}i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest=$destfile destfile= ;; *) func_fatal_help "cannot copy a libtool object to '$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test yes = "$build_old_libs"; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile=$destdir/$destname else func_basename "$file" destfile=$func_basename_result destfile=$destdir/$destfile fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext= case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=.exe fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script '$wrapper'" finalize=: for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile=$libdir/`$ECHO "$lib" | $SED 's%^.*/%%g'` if test -n "$libdir" && test ! -f "$libfile"; then func_warning "'$lib' has not been installed in '$libdir'" finalize=false fi done relink_command= func_source "$wrapper" outputname= if test no = "$fast_install" && test -n "$relink_command"; then $opt_dry_run || { if $finalize; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file=$func_basename_result outputname=$tmpdir/$file # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_quiet || { func_quote_arg expand,pretty "$relink_command" eval "func_echo $func_quote_arg_result" } if eval "$relink_command"; then : else func_error "error: relink '$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file=$outputname else func_warning "cannot relink '$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name=$func_basename_result # Set up the ranlib parameters. oldlib=$destdir/$name func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run '$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL "$progpath" $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test install = "$opt_mode" && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $debug_cmd my_outputname=$1 my_originator=$2 my_pic_p=${3-false} my_prefix=`$ECHO "$my_originator" | $SED 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms=${my_outputname}S.c else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist=$output_objdir/$my_outputname.nm func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* External symbol declarations for the compiler. */\ " if test yes = "$dlself"; then func_verbose "generating symbol list for '$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from '$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols=$output_objdir/$outputname.exp $opt_dry_run || { $RM $export_symbols eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "$SED -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from '$dlprefile'" func_basename "$dlprefile" name=$func_basename_result case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename= if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname"; then func_basename "$dlprefile_dlname" dlprefile_dlbasename=$func_basename_result else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename"; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi func_show_eval '$RM "${nlist}I"' if test -n "$global_symbol_to_import"; then eval "$global_symbol_to_import"' < "$nlist"S > "$nlist"I' fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[];\ " if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ static void lt_syminit(void) { LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols; for (; symbol->name; ++symbol) {" $SED 's/.*/ if (STREQ (symbol->name, \"&\")) symbol->address = (void *) \&&;/' < "$nlist"I >> "$output_objdir/$my_dlsyms" echo >> "$output_objdir/$my_dlsyms" "\ } }" fi echo >> "$output_objdir/$my_dlsyms" "\ LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = { {\"$my_originator\", (void *) 0}," if test -s "$nlist"I; then echo >> "$output_objdir/$my_dlsyms" "\ {\"@INIT@\", (void *) <_syminit}," fi case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) $my_pic_p && pic_flag_for_symtable=" $pic_flag" ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T" "${nlist}I"' # Transform the symbol file into the correct name. symfileobj=$output_objdir/${my_outputname}S.$objext case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for '$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $debug_cmd func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $debug_cmd win32_libid_type=unknown win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then case $nm_interface in "MS dumpbin") if func_cygming_ms_implib_p "$1" || func_cygming_gnu_implib_p "$1" then win32_nmres=import else win32_nmres= fi ;; *) func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s|.*|import| p q } }'` ;; esac case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $debug_cmd sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $debug_cmd match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive that possess that section. Heuristic: eliminate # all those that have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $debug_cmd if func_cygming_gnu_implib_p "$1"; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1"; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result= fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $debug_cmd f_ex_an_ar_dir=$1; shift f_ex_an_ar_oldlib=$1 if test yes = "$lock_old_archive_extraction"; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test yes = "$lock_old_archive_extraction"; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $debug_cmd my_gentop=$1; shift my_oldlibs=${1+"$@"} my_oldobjs= my_xlib= my_xabs= my_xdir= for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs=$my_xlib ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib=$func_basename_result my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir=$my_gentop/$my_xlib_u func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` func_basename "$darwin_archive" darwin_base_archive=$func_basename_result darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches; do func_mkdir_p "unfat-$$/$darwin_base_archive-$darwin_arch" $LIPO -thin $darwin_arch -output "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" "$darwin_archive" cd "unfat-$$/$darwin_base_archive-$darwin_arch" func_extract_an_archive "`pwd`" "$darwin_base_archive" cd "$darwin_curdir" $RM "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$sed_basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result=$my_oldobjs } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory where it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" func_quote_arg pretty "$ECHO" qECHO=$func_quote_arg_result $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=$qECHO fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ that is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options that match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"$outputname:$output:\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"$outputname:$output:\$LINENO: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test yes = "$fast_install"; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | $SED 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else \$ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: '\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include #define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0) /* declarations of non-ANSI functions */ #if defined __MINGW32__ # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined __CYGWIN__ # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined other_platform || defined ... */ #endif /* portability defines, excluding path handling macros */ #if defined _MSC_VER # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC #elif defined __MINGW32__ # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined __CYGWIN__ # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined other platforms ... */ #endif #if defined PATH_MAX # define LT_PATHMAX PATH_MAX #elif defined MAXPATHLEN # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \ defined __OS2__ # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free (stale); stale = 0; } \ } while (0) #if defined LT_DEBUGWRAPPER static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; size_t tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined HAVE_DOS_BASED_FILE_SYSTEM if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined HAVE_DOS_BASED_FILE_SYSTEM } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = (size_t) (q - p); p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (STREQ (str, pat)) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else size_t len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { size_t orig_value_len = strlen (orig_value); size_t add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ size_t len = strlen (new_value); while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[--len] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $debug_cmd case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_suncc_cstd_abi # !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!! # Several compiler flags select an ABI that is incompatible with the # Cstd library. Avoid specifying it if any are in CXXFLAGS. func_suncc_cstd_abi () { $debug_cmd case " $compile_command " in *" -compat=g "*|*\ -std=c++[0-9][0-9]\ *|*" -library=stdcxx4 "*|*" -library=stlport4 "*) suncc_use_cstd_abi=no ;; *) suncc_use_cstd_abi=yes ;; esac } # func_mode_link arg... func_mode_link () { $debug_cmd case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # what system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll that has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= os2dllname= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=false prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module=$wl-single_module func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test yes != "$build_libtool_libs" \ && func_fatal_configuration "cannot build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test yes = "$build_libtool_libs" && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg=$1 shift func_quote_arg pretty,unquoted "$arg" qarg=$func_quote_arg_unquoted_result func_append libtool_args " $func_quote_arg_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir=$arg prev= continue ;; dlfiles|dlprefiles) $preload || { # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=: } case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test no = "$dlself"; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test dlprefiles = "$prev"; then dlself=yes elif test dlfiles = "$prev" && test yes != "$dlopen_self"; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test dlfiles = "$prev"; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols=$arg test -f "$arg" \ || func_fatal_error "symbol file '$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex=$arg prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir=$arg prev= continue ;; mllvm) # Clang does not use LLVM to link, so we can simply discard any # '-mllvm $arg' options when doing the link step. prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result if test none != "$pic_object"; then # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object fi # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file '$arg' does not exist" fi arg=$save_arg prev= continue ;; os2dllname) os2dllname=$arg prev= continue ;; precious_regex) precious_files_regex=$arg prev= continue ;; release) release=-$arg prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test rpath = "$prev"; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds=$arg prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg=$arg case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "'-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test X-export-symbols = "X$arg"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between '-L' and '$1'" else func_fatal_error "need path for '-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of '$dir'" dir=$absdir ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test X-lc = "X$arg" || test X-lm = "X$arg"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test X-lc = "X$arg" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc due to us having libc/libc_r. test X-lc = "X$arg" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test X-lc = "X$arg" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test X-lc = "X$arg" && continue ;; esac elif test X-lc_r = "X$arg"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -mllvm) prev=mllvm continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module=$wl-multi_module continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "'-no-install' is ignored for $host" func_warning "assuming '-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -os2dllname) prev=os2dllname continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_arg pretty "$flag" func_append arg " $func_quote_arg_result" func_append compiler_flags " $func_quote_arg_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs=$IFS; IFS=, for flag in $args; do IFS=$save_ifs func_quote_arg pretty "$flag" func_append arg " $wl$func_quote_arg_result" func_append compiler_flags " $wl$func_quote_arg_result" func_append linker_flags " $func_quote_arg_result" done IFS=$save_ifs func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_arg pretty "$arg" arg=$func_quote_arg_result ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # -fstack-protector* stack protector flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization # -specs=* GCC specs files # -stdlib=* select c++ std lib with clang # -fsanitize=* Clang/GCC memory and address sanitizer -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \ -specs=*|-fsanitize=*) func_quote_arg pretty "$arg" arg=$func_quote_arg_result func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; -Z*) if test os2 = "`expr $host : '.*\(os2\)'`"; then # OS/2 uses -Zxxx to specify OS/2-specific options compiler_flags="$compiler_flags $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case $arg in -Zlinker | -Zstack) prev=xcompiler ;; esac continue else # Otherwise treat like 'Some other compiler flag' below func_quote_arg pretty "$arg" arg=$func_quote_arg_result fi ;; # Some other compiler flag. -* | +*) func_quote_arg pretty "$arg" arg=$func_quote_arg_result ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test none = "$pic_object" && test none = "$non_pic_object"; then func_fatal_error "cannot find name of object for '$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result test none = "$pic_object" || { # Prepend the subdirectory the object is found in. pic_object=$xdir$pic_object if test dlfiles = "$prev"; then if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test dlprefiles = "$prev"; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg=$pic_object } # Non-PIC object. if test none != "$non_pic_object"; then # Prepend the subdirectory the object is found in. non_pic_object=$xdir$non_pic_object # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test none = "$pic_object"; then arg=$non_pic_object fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object=$pic_object func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir=$func_dirname_result func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "'$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test dlfiles = "$prev"; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test dlprefiles = "$prev"; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_arg pretty "$arg" arg=$func_quote_arg_result ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the '$prevarg' option requires an argument" if test yes = "$export_dynamic" && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname=$func_basename_result libobjs_save=$libobjs if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\$$shlibpath_var\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" # Definition is injected by LT_CONFIG during libtool generation. func_munge_path_list sys_lib_dlsearch_path "$LT_SYS_LIBRARY_PATH" func_dirname "$output" "/" "" output_objdir=$func_dirname_result$objdir func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test lib = "$linkmode"; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can '-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=false newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test lib,link = "$linkmode,$pass"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs=$tmp_deplibs fi if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass"; then libs=$deplibs deplibs= fi if test prog = "$linkmode"; then case $pass in dlopen) libs=$dlfiles ;; dlpreopen) libs=$dlprefiles ;; link) libs="$deplibs %DEPLIBS%" test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" ;; esac fi if test lib,dlpreopen = "$linkmode,$pass"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs=$dlprefiles fi if test dlopen = "$pass"; then # Collect dlpreopened libraries save_deplibs=$deplibs deplibs= fi for deplib in $libs; do lib= found=false case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test lib != "$linkmode" && test prog != "$linkmode"; then func_warning "'-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test lib = "$linkmode"; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib=$searchdir/lib$name$search_ext if test -f "$lib"; then if test .la = "$search_ext"; then found=: else found=false fi break 2 fi done done if $found; then # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll=$l done if test "X$ll" = "X$old_library"; then # only static version available found=false func_dirname "$lib" "" "." ladir=$func_dirname_result lib=$ladir/$old_library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi else # deplib doesn't seem to be a libtool library if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs" fi continue fi ;; # -l *.ltframework) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test lib = "$linkmode"; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test conv = "$pass" && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi if test scan = "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "'-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test link = "$pass"; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test conv = "$pass"; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=false case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=: fi ;; pass_all) valid_a_lib=: ;; esac if $valid_a_lib; then echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" else echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." fi ;; esac continue ;; prog) if test link != "$pass"; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test conv = "$pass"; then deplibs="$deplib $deplibs" elif test prog = "$linkmode"; then if test dlpreopen = "$pass" || test yes != "$dlopen_support" || test no = "$build_libtool_libs"; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=: continue ;; esac # case $deplib $found || test -f "$lib" \ || func_fatal_error "cannot find the library '$lib' or unhandled argument '$deplib'" # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "'$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir=$func_dirname_result dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test lib,link = "$linkmode,$pass" || test prog,scan = "$linkmode,$pass" || { test prog != "$linkmode" && test lib != "$linkmode"; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test conv = "$pass"; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for '$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done elif test prog != "$linkmode" && test lib != "$linkmode"; then func_fatal_error "'$lib' is not a convenience library" fi continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test yes = "$prefer_static_libs" || test built,no = "$prefer_static_libs,$installed"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib=$l done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for '$lib'" fi # This library was specified with -dlopen. if test dlopen = "$pass"; then test -z "$libdir" \ && func_fatal_error "cannot -dlopen a convenience library: '$lib'" if test -z "$dlname" || test yes != "$dlopen_support" || test no = "$build_libtool_libs" then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir=$ladir ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of '$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir=$ladir fi ;; esac func_basename "$lib" laname=$func_basename_result # Find the relevant object directory and library name. if test yes = "$installed"; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library '$lib' was moved." dir=$ladir absdir=$abs_ladir libdir=$abs_ladir else dir=$lt_sysroot$libdir absdir=$lt_sysroot$libdir fi test yes = "$hardcode_automatic" && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir=$ladir absdir=$abs_ladir # Remove this search path later func_append notinst_path " $abs_ladir" else dir=$ladir/$objdir absdir=$abs_ladir/$objdir # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test dlpreopen = "$pass"; then if test -z "$libdir" && test prog = "$linkmode"; then func_fatal_error "only libraries may -dlpreopen a convenience library: '$lib'" fi case $host in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test lib = "$linkmode"; then deplibs="$dir/$old_library $deplibs" elif test prog,link = "$linkmode,$pass"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test prog = "$linkmode" && test link != "$pass"; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=false if test no != "$link_all_deplibs" || test -z "$library_names" || test no = "$build_libtool_libs"; then linkalldeplibs=: fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if $linkalldeplibs; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test prog,link = "$linkmode,$pass"; then if test -n "$library_names" && { { test no = "$prefer_static_libs" || test built,yes = "$prefer_static_libs,$installed"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath"; then # Make sure the rpath contains only unique directories. case $temp_rpath: in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if $alldeplibs && { test pass_all = "$deplibs_check_method" || { test yes = "$build_libtool_libs" && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test built = "$use_static_libs" && test yes = "$installed"; then use_static_libs=no fi if test -n "$library_names" && { test no = "$use_static_libs" || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc* | *os2*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test no = "$installed"; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule= for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule=$dlpremoduletest break fi done if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then echo if test prog = "$linkmode"; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test lib = "$linkmode" && test yes = "$hardcode_into_libs"; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname=$1 shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname=$dlname elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc* | *os2*) func_arith $current - $age major=$func_arith_result versuffix=-$major ;; esac eval soname=\"$soname_spec\" else soname=$realname fi # Make a new name for the extract_expsyms_cmds to use soroot=$soname func_basename "$soroot" soname=$func_basename_result func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from '$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for '$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test prog = "$linkmode" || test relink != "$opt_mode"; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test no = "$hardcode_direct"; then add=$dir/$linklib case $host in *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;; *-*-sysv4*uw2*) add_dir=-L$dir ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir=-L$dir ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we cannot # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library"; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add=$dir/$old_library fi elif test -n "$old_library"; then add=$dir/$old_library fi fi esac elif test no = "$hardcode_minus_L"; then case $host in *-*-sunos*) add_shlibpath=$dir ;; esac add_dir=-L$dir add=-l$name elif test no = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; relink) if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$dir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$absdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name elif test yes = "$hardcode_shlibpath_var"; then add_shlibpath=$dir add=-l$name else lib_linked=no fi ;; *) lib_linked=no ;; esac if test yes != "$lib_linked"; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test prog = "$linkmode"; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test yes != "$hardcode_direct" && test yes != "$hardcode_minus_L" && test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test prog = "$linkmode" || test relink = "$opt_mode"; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test yes = "$hardcode_direct" && test no = "$hardcode_direct_absolute"; then add=$libdir/$linklib elif test yes = "$hardcode_minus_L"; then add_dir=-L$libdir add=-l$name elif test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add=-l$name elif test yes = "$hardcode_automatic"; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib"; then add=$inst_prefix_dir$libdir/$linklib else add=$libdir/$linklib fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir=-L$libdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add=-l$name fi if test prog = "$linkmode"; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test prog = "$linkmode"; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test unsupported != "$hardcode_direct"; then test -n "$old_library" && linklib=$old_library compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test yes = "$build_libtool_libs"; then # Not a shared library if test pass_all != "$deplibs_check_method"; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system cannot link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test yes = "$module"; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test lib = "$linkmode"; then if test -n "$dependency_libs" && { test yes != "$hardcode_into_libs" || test yes = "$build_old_libs" || test yes = "$link_static"; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs=$temp_deplibs fi func_append newlib_search_path " $absdir" # Link against this library test no = "$link_static" && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test no != "$link_all_deplibs"; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path=$deplib ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir=$dir ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of '$dir'" absdir=$dir fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`$SED -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names"; then for tmp in $deplibrary_names; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl"; then depdepl=$absdir/$objdir/$depdepl darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`$OTOOL64 -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " $wl-dylib_file $wl$darwin_install_name:$depdepl" func_append linker_flags " -dylib_file $darwin_install_name:$depdepl" path= fi fi ;; *) path=-L$absdir/$objdir ;; esac else eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "'$deplib' seems to be moved" path=-L$absdir fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test link = "$pass"; then if test prog = "$linkmode"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs=$newdependency_libs if test dlpreopen = "$pass"; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test dlopen != "$pass"; then test conv = "$pass" || { # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= } if test prog,link = "$linkmode,$pass"; then vars="compile_deplibs finalize_deplibs" else vars=deplibs fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Add Sun CC postdeps if required: test CXX = "$tagname" && { case $host_os in linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; solaris*) func_cc_basename "$CC" case $func_cc_basename_result in CC* | sunCC*) func_suncc_cstd_abi if test no != "$suncc_use_cstd_abi"; then func_append postdeps ' -library=Cstd -library=Crun' fi ;; esac ;; esac } # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i= ;; esac if test -n "$i"; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test prog = "$linkmode"; then dlfiles=$newdlfiles fi if test prog = "$linkmode" || test lib = "$linkmode"; then dlprefiles=$newdlprefiles fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "'-R' is ignored for archives" test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "'-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "'-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs=$output func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form 'libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test no = "$module" \ && func_fatal_help "libtool library '$output' must begin with 'lib'" if test no != "$need_lib_prefix"; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test pass_all != "$deplibs_check_method"; then func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test no = "$dlself" \ || func_warning "'-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test 1 -lt "$#" \ && func_warning "ignoring multiple '-rpath's for a libtool library" install_libdir=$1 oldlibs= if test -z "$rpath"; then if test yes = "$build_libtool_libs"; then # Building a libtool convenience library. # Some compilers have problems with a '.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "'-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "'-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs=$IFS; IFS=: set dummy $vinfo 0 0 0 shift IFS=$save_ifs test -n "$7" && \ func_fatal_help "too many parameters to '-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major=$1 number_minor=$2 number_revision=$3 # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # that has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|freebsd-elf|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_revision ;; freebsd-aout|qnx|sunos) current=$number_major revision=$number_minor age=0 ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_minor lt_irix_increment=no ;; *) func_fatal_configuration "$modename: unknown library version type '$version_type'" ;; esac ;; no) current=$1 revision=$2 age=$3 ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT '$current' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION '$revision' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE '$age' must be a nonnegative integer" func_fatal_error "'$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE '$age' is greater than the current interface number '$current'" func_fatal_error "'$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" # On Darwin other compilers case $CC in nagfor*) verstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision" ;; *) verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; esac ;; freebsd-aout) major=.$current versuffix=.$current.$revision ;; freebsd-elf) func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; irix | nonstopux) if test no = "$lt_irix_increment"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring=$verstring_prefix$major.$revision # Add in all the interfaces that we are compatible with. loop=$revision while test 0 -ne "$loop"; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring_prefix$major.$iface:$verstring done # Before this point, $major must not contain '.'. major=.$major versuffix=$major.$revision ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix=$major.$age.$revision ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=.$current.$age.$revision verstring=$current.$age.$revision # Add in all the interfaces that we are compatible with. loop=$age while test 0 -ne "$loop"; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring=$verstring:$iface.0 done # Make executables depend on our current version. func_append verstring ":$current.0" ;; qnx) major=.$current versuffix=.$current ;; sco) major=.$current versuffix=.$current ;; sunos) major=.$current versuffix=.$current.$revision ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 file systems. func_arith $current - $age major=$func_arith_result versuffix=-$major ;; *) func_fatal_configuration "unknown library version type '$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring=0.0 ;; esac if test no = "$need_version"; then versuffix= else versuffix=.0.0 fi fi # Remove version info from name if versioning should be avoided if test yes,no = "$avoid_version,$need_version"; then major= versuffix= verstring= fi # Check to see if the archive will have undefined symbols. if test yes = "$allow_undefined"; then if test unsupported = "$allow_undefined_flag"; then if test yes = "$build_old_libs"; then func_warning "undefined symbols not allowed in $host shared libraries; building static only" build_libtool_libs=no else func_fatal_error "can't build $host shared library unless -no-undefined is specified" fi fi else # Don't allow undefined symbols. allow_undefined_flag=$no_undefined_flag fi fi func_generate_dlsyms "$libname" "$libname" : func_append libobjs " $symfileobj" test " " = "$libobjs" && libobjs= if test relink != "$opt_mode"; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*) if test -n "$precious_files_regex"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test yes = "$build_old_libs" && test convenience != "$build_libtool_libs"; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test yes != "$hardcode_into_libs" || test yes = "$build_old_libs"; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles=$dlfiles dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles=$dlprefiles dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test yes = "$build_libtool_libs"; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test yes = "$build_libtool_need_lc"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release= versuffix= major= newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib=$potent_lib while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | $SED 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib=$potliblink;; *) potlib=`$ECHO "$potlib" | $SED 's|[^/]*$||'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test yes = "$allow_libtool_libs_with_static_runtimes"; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib= ;; esac fi if test -n "$a_deplib"; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib=$potent_lib # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib= break 2 fi done done fi if test -n "$a_deplib"; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib"; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs= tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test yes = "$allow_libtool_libs_with_static_runtimes"; then for i in $predeps $postdeps; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s|$i||"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test none = "$deplibs_check_method"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test yes = "$droppeddeps"; then if test yes = "$module"; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using 'nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** 'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test no = "$allow_undefined"; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs=$new_libs # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test yes = "$build_libtool_libs"; then # Remove $wl instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test yes = "$hardcode_into_libs"; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath=$finalize_rpath test relink = "$opt_mode" || rpath=$compile_rpath$rpath for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath=$finalize_shlibpath test relink = "$opt_mode" || shlibpath=$compile_shlibpath$shlibpath if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname=$1 shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname=$realname fi if test -z "$dlname"; then dlname=$soname fi lib=$output_objdir/$realname linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols=$output_objdir/$libname.uexp func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile func_dll_def_p "$export_symbols" || { # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols=$export_symbols export_symbols= always_export_symbols=yes } fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test yes = "$always_export_symbols" || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs=$IFS; IFS='~' for cmd1 in $cmds; do IFS=$save_ifs # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test yes = "$try_normal_branch" \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=$output_objdir/$output_la.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS=$save_ifs if test -n "$export_symbols_regex" && test : != "$skipped_export"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test : != "$skipped_export" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs=$tmp_deplibs if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test yes = "$compiler_needs_object" && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test yes = "$thread_safe" && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test : != "$skipped_export" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then output=$output_objdir/$output_la.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then output=$output_objdir/$output_la.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test yes = "$compiler_needs_object"; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-$k.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test -z "$objlist" || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test 1 -eq "$k"; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-$k.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-$k.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi ${skipped_export-false} && { func_verbose "generating symbol list for '$libname.la'" export_symbols=$output_objdir/$libname.exp $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi } test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs=$IFS; IFS='~' for cmd in $concat_cmds; do IFS=$save_ifs $opt_quiet || { func_quote_arg expand,pretty "$cmd" eval "func_echo $func_quote_arg_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi ${skipped_export-false} && { if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols=$export_symbols test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for '$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands, which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi } libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test yes = "$module" && test -n "$module_cmds"; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs=$IFS; IFS='~' for cmd in $cmds; do IFS=$sp$nl eval cmd=\"$cmd\" IFS=$save_ifs $opt_quiet || { func_quote_arg expand,pretty "$cmd" eval "func_echo $func_quote_arg_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test relink = "$opt_mode"; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS=$save_ifs # Restore the uninstalled library and exit if test relink = "$opt_mode"; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test yes = "$module" || test yes = "$export_dynamic"; then # On all known operating systems, these are identical. dlname=$soname fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then func_warning "'-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "'-l' and '-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "'-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "'-R' is ignored for objects" test -n "$vinfo" && \ func_warning "'-version-info' is ignored for objects" test -n "$release" && \ func_warning "'-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object '$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj=$output ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # if reload_cmds runs $LD directly, get rid of -Wl from # whole_archive_flag_spec and hope we can get by with turning comma # into space. case $reload_cmds in *\$LD[\ \$]*) wl= ;; esac if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" test -n "$wl" || tmp_whole_archive_flags=`$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` reload_conv_objs=$reload_objs\ $tmp_whole_archive_flags else gentop=$output_objdir/${obj}x func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test yes = "$build_libtool_libs" || libobjs=$non_pic_objects # Create the old-style object. reload_objs=$objs$old_deplibs' '`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; /\.lib$/d; $lo2o" | $NL2SP`' '$reload_conv_objs output=$obj func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi test yes = "$build_libtool_libs" || { if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS } if test -n "$pic_flag" || test default != "$pic_mode"; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output=$libobj func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "'-version-info' is ignored for programs" test -n "$release" && \ func_warning "'-release' is ignored for programs" $preload \ && test unknown,unknown,unknown = "$dlopen_support,$dlopen_self,$dlopen_self_static" \ && func_warning "'LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test CXX = "$tagname"; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " $wl-bind_at_load" func_append finalize_command " $wl-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs=$new_libs func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath=$rpath rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs=$libdir else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir=$hardcode_libdirs eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath=$rpath if test -n "$libobjs" && test yes = "$build_old_libs"; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" false # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=: case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=false ;; *cygwin* | *mingw* ) test yes = "$build_libtool_libs" || wrappers_required=false ;; *) if test no = "$need_relink" || test yes != "$build_libtool_libs"; then wrappers_required=false fi ;; esac $wrappers_required || { # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command=$compile_command$compile_rpath # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.$objext"; then func_show_eval '$RM "$output_objdir/${outputname}S.$objext"' fi exit $exit_status } if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test yes = "$no_install"; then # We don't need to create a wrapper script. link_command=$compile_var$compile_command$compile_rpath # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi case $hardcode_action,$fast_install in relink,*) # Fast installation is not supported link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath func_warning "this platform does not like uninstalled shared libraries" func_warning "'$output' will be relinked during installation" ;; *,yes) link_command=$finalize_var$compile_command$finalize_rpath relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` ;; *,no) link_command=$compile_var$compile_command$compile_rpath relink_command=$finalize_var$finalize_command$finalize_rpath ;; *,needless) link_command=$finalize_var$compile_command$finalize_rpath relink_command= ;; esac # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_arg pretty "$var_value" relink_command="$var=$func_quote_arg_result; export $var; $relink_command" fi done func_quote_arg pretty,unquoted "(cd `pwd`; $relink_command)" relink_command=$func_quote_arg_unquoted_result fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource=$output_path/$objdir/lt-$output_name.c cwrapper=$output_path/$output_name.exe $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host"; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do case $build_libtool_libs in convenience) oldobjs="$libobjs_save $symfileobj" addlibs=$convenience build_libtool_libs=no ;; module) oldobjs=$libobjs_save addlibs=$old_convenience build_libtool_libs=no ;; *) oldobjs="$old_deplibs $non_pic_objects" $preload && test -f "$symfileobj" \ && func_append oldobjs " $symfileobj" addlibs=$old_convenience ;; esac if test -n "$addlibs"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test yes = "$build_libtool_libs"; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop=$output_objdir/${outputname}x func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase=$func_basename_result case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj"; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test -z "$oldobjs"; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test yes = "$build_old_libs" && old_library=$libname.$libext func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_arg pretty,unquoted "$var_value" relink_command="$var=$func_quote_arg_unquoted_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL \"$progpath\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" func_quote_arg pretty,unquoted "$relink_command" relink_command=$func_quote_arg_unquoted_result if test yes = "$hardcode_automatic"; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test yes = "$installed"; then if test -z "$install_libdir"; then break fi output=$output_objdir/${outputname}i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name=$func_basename_result func_resolve_sysroot "$deplib" eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "'$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs=$newdependency_libs newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name=$func_basename_result eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "'$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles=$newdlprefiles else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles=$newdlfiles newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles=$newdlprefiles fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test -n "$bindir"; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result/$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that cannot go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test no,yes = "$installed,$need_relink"; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } if test link = "$opt_mode" || test relink = "$opt_mode"; then func_mode_link ${1+"$@"} fi # func_mode_uninstall arg... func_mode_uninstall () { $debug_cmd RM=$nonopt files= rmforce=false exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic=$magic for arg do case $arg in -f) func_append RM " $arg"; rmforce=: ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir=$func_dirname_result if test . = "$dir"; then odir=$objdir else odir=$dir/$objdir fi func_basename "$file" name=$func_basename_result test uninstall = "$opt_mode" && odir=$dir # Remember odir for removal later, being careful to avoid duplicates if test clean = "$opt_mode"; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif $rmforce; then continue fi rmfiles=$file case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case $opt_mode in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" '$rmforce || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" '$rmforce || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test none != "$pic_object"; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test none != "$non_pic_object"; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test clean = "$opt_mode"; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.$objext" if test yes = "$fast_install" && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name"; then func_append rmfiles " $odir/lt-$noexename.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the $objdir's in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } if test uninstall = "$opt_mode" || test clean = "$opt_mode"; then func_mode_uninstall ${1+"$@"} fi test -z "$opt_mode" && { help=$generic_help func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode '$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # where we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: getdns-1.5.1/src/0000755000175000017500000000000013416117763010603 500000000000000getdns-1.5.1/src/util/0000755000175000017500000000000013416117763011560 500000000000000getdns-1.5.1/src/util/val_secalgo.c0000644000175000017500000014015313416117763014127 00000000000000/* * validator/val_secalgo.c - validator security algorithm functions. * * Copyright (c) 2012, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. */ /** * \file * * This file contains helper functions for the validator module. * These functions take raw data buffers, formatted for crypto verification, * and do the library calls (for the crypto library in use). */ #include "config.h" /* packed_rrset on top to define enum types (forced by c99 standard) */ #include "util/data/packed_rrset.h" #include "validator/val_secalgo.h" #include "validator/val_nsec3.h" #include "util/log.h" #include "sldns/rrdef.h" #include "sldns/keyraw.h" #include "sldns/sbuffer.h" #if !defined(HAVE_SSL) && !defined(HAVE_NSS) && !defined(HAVE_NETTLE) #error "Need crypto library to do digital signature cryptography" #endif /* OpenSSL implementation */ #ifdef HAVE_SSL #ifdef HAVE_OPENSSL_ERR_H #include #endif #ifdef HAVE_OPENSSL_RAND_H #include #endif #ifdef HAVE_OPENSSL_CONF_H #include #endif #ifdef HAVE_OPENSSL_ENGINE_H #include #endif /** fake DSA support for unit tests */ int fake_dsa = 0; /** fake SHA1 support for unit tests */ int fake_sha1 = 0; /** * Output a libcrypto openssl error to the logfile. * @param str: string to add to it. * @param e: the error to output, error number from ERR_get_error(). */ static void log_crypto_error(const char* str, unsigned long e) { char buf[128]; /* or use ERR_error_string if ERR_error_string_n is not avail TODO */ ERR_error_string_n(e, buf, sizeof(buf)); /* buf now contains */ /* error:[error code]:[library name]:[function name]:[reason string] */ log_err("%s crypto %s", str, buf); } /* return size of digest if supported, or 0 otherwise */ size_t nsec3_hash_algo_size_supported(int id) { switch(id) { case NSEC3_HASH_SHA1: return SHA_DIGEST_LENGTH; default: return 0; } } /* perform nsec3 hash. return false on failure */ int secalgo_nsec3_hash(int algo, unsigned char* buf, size_t len, unsigned char* res) { switch(algo) { case NSEC3_HASH_SHA1: #ifdef OPENSSL_FIPS if(!sldns_digest_evp(buf, len, res, EVP_sha1())) log_crypto_error("could not digest with EVP_sha1", ERR_get_error()); #else (void)SHA1(buf, len, res); #endif return 1; default: return 0; } } void secalgo_hash_sha256(unsigned char* buf, size_t len, unsigned char* res) { #ifdef OPENSSL_FIPS if(!sldns_digest_evp(buf, len, res, EVP_sha256())) log_crypto_error("could not digest with EVP_sha256", ERR_get_error()); #else (void)SHA256(buf, len, res); #endif } /** * Return size of DS digest according to its hash algorithm. * @param algo: DS digest algo. * @return size in bytes of digest, or 0 if not supported. */ size_t ds_digest_size_supported(int algo) { switch(algo) { case LDNS_SHA1: #if defined(HAVE_EVP_SHA1) && defined(USE_SHA1) return SHA_DIGEST_LENGTH; #else if(fake_sha1) return 20; return 0; #endif #ifdef HAVE_EVP_SHA256 case LDNS_SHA256: return SHA256_DIGEST_LENGTH; #endif #ifdef USE_GOST case LDNS_HASH_GOST: /* we support GOST if it can be loaded */ (void)sldns_key_EVP_load_gost_id(); if(EVP_get_digestbyname("md_gost94")) return 32; else return 0; #endif #ifdef USE_ECDSA case LDNS_SHA384: return SHA384_DIGEST_LENGTH; #endif default: break; } return 0; } #ifdef USE_GOST /** Perform GOST hash */ static int do_gost94(unsigned char* data, size_t len, unsigned char* dest) { const EVP_MD* md = EVP_get_digestbyname("md_gost94"); if(!md) return 0; return sldns_digest_evp(data, (unsigned int)len, dest, md); } #endif int secalgo_ds_digest(int algo, unsigned char* buf, size_t len, unsigned char* res) { switch(algo) { #if defined(HAVE_EVP_SHA1) && defined(USE_SHA1) case LDNS_SHA1: #ifdef OPENSSL_FIPS if(!sldns_digest_evp(buf, len, res, EVP_sha1())) log_crypto_error("could not digest with EVP_sha1", ERR_get_error()); #else (void)SHA1(buf, len, res); #endif return 1; #endif #ifdef HAVE_EVP_SHA256 case LDNS_SHA256: #ifdef OPENSSL_FIPS if(!sldns_digest_evp(buf, len, res, EVP_sha256())) log_crypto_error("could not digest with EVP_sha256", ERR_get_error()); #else (void)SHA256(buf, len, res); #endif return 1; #endif #ifdef USE_GOST case LDNS_HASH_GOST: if(do_gost94(buf, len, res)) return 1; break; #endif #ifdef USE_ECDSA case LDNS_SHA384: #ifdef OPENSSL_FIPS if(!sldns_digest_evp(buf, len, res, EVP_sha384())) log_crypto_error("could not digest with EVP_sha384", ERR_get_error()); #else (void)SHA384(buf, len, res); #endif return 1; #endif default: verbose(VERB_QUERY, "unknown DS digest algorithm %d", algo); break; } return 0; } /** return true if DNSKEY algorithm id is supported */ int dnskey_algo_id_is_supported(int id) { switch(id) { case LDNS_RSAMD5: /* RFC 6725 deprecates RSAMD5 */ return 0; case LDNS_DSA: case LDNS_DSA_NSEC3: #if defined(USE_DSA) && defined(USE_SHA1) return 1; #else if(fake_dsa || fake_sha1) return 1; return 0; #endif case LDNS_RSASHA1: case LDNS_RSASHA1_NSEC3: #ifdef USE_SHA1 return 1; #else if(fake_sha1) return 1; return 0; #endif #if defined(HAVE_EVP_SHA256) && defined(USE_SHA2) case LDNS_RSASHA256: #endif #if defined(HAVE_EVP_SHA512) && defined(USE_SHA2) case LDNS_RSASHA512: #endif #ifdef USE_ECDSA case LDNS_ECDSAP256SHA256: case LDNS_ECDSAP384SHA384: #endif #ifdef USE_ED25519 case LDNS_ED25519: #endif #ifdef USE_ED448 case LDNS_ED448: #endif #if (defined(HAVE_EVP_SHA256) && defined(USE_SHA2)) || (defined(HAVE_EVP_SHA512) && defined(USE_SHA2)) || defined(USE_ECDSA) || defined(USE_ED25519) || defined(USE_ED448) return 1; #endif #ifdef USE_GOST case LDNS_ECC_GOST: /* we support GOST if it can be loaded */ return sldns_key_EVP_load_gost_id(); #endif default: return 0; } } #ifdef USE_DSA /** * Setup DSA key digest in DER encoding ... * @param sig: input is signature output alloced ptr (unless failure). * caller must free alloced ptr if this routine returns true. * @param len: input is initial siglen, output is output len. * @return false on failure. */ static int setup_dsa_sig(unsigned char** sig, unsigned int* len) { unsigned char* orig = *sig; unsigned int origlen = *len; int newlen; BIGNUM *R, *S; DSA_SIG *dsasig; /* extract the R and S field from the sig buffer */ if(origlen < 1 + 2*SHA_DIGEST_LENGTH) return 0; R = BN_new(); if(!R) return 0; (void) BN_bin2bn(orig + 1, SHA_DIGEST_LENGTH, R); S = BN_new(); if(!S) return 0; (void) BN_bin2bn(orig + 21, SHA_DIGEST_LENGTH, S); dsasig = DSA_SIG_new(); if(!dsasig) return 0; #ifdef HAVE_DSA_SIG_SET0 if(!DSA_SIG_set0(dsasig, R, S)) return 0; #else dsasig->r = R; dsasig->s = S; #endif *sig = NULL; newlen = i2d_DSA_SIG(dsasig, sig); if(newlen < 0) { DSA_SIG_free(dsasig); free(*sig); return 0; } *len = (unsigned int)newlen; DSA_SIG_free(dsasig); return 1; } #endif /* USE_DSA */ #ifdef USE_ECDSA /** * Setup the ECDSA signature in its encoding that the library wants. * Converts from plain numbers to ASN formatted. * @param sig: input is signature, output alloced ptr (unless failure). * caller must free alloced ptr if this routine returns true. * @param len: input is initial siglen, output is output len. * @return false on failure. */ static int setup_ecdsa_sig(unsigned char** sig, unsigned int* len) { /* convert from two BIGNUMs in the rdata buffer, to ASN notation. * ASN preamble: 30440220 0220 * the '20' is the length of that field (=bnsize). i * the '44' is the total remaining length. * if negative, start with leading zero. * if starts with 00s, remove them from the number. */ uint8_t pre[] = {0x30, 0x44, 0x02, 0x20}; int pre_len = 4; uint8_t mid[] = {0x02, 0x20}; int mid_len = 2; int raw_sig_len, r_high, s_high, r_rem=0, s_rem=0; int bnsize = (int)((*len)/2); unsigned char* d = *sig; uint8_t* p; /* if too short or not even length, fails */ if(*len < 16 || bnsize*2 != (int)*len) return 0; /* strip leading zeroes from r (but not last one) */ while(r_rem < bnsize-1 && d[r_rem] == 0) r_rem++; /* strip leading zeroes from s (but not last one) */ while(s_rem < bnsize-1 && d[bnsize+s_rem] == 0) s_rem++; r_high = ((d[0+r_rem]&0x80)?1:0); s_high = ((d[bnsize+s_rem]&0x80)?1:0); raw_sig_len = pre_len + r_high + bnsize - r_rem + mid_len + s_high + bnsize - s_rem; *sig = (unsigned char*)malloc((size_t)raw_sig_len); if(!*sig) return 0; p = (uint8_t*)*sig; p[0] = pre[0]; p[1] = (uint8_t)(raw_sig_len-2); p[2] = pre[2]; p[3] = (uint8_t)(bnsize + r_high - r_rem); p += 4; if(r_high) { *p = 0; p += 1; } memmove(p, d+r_rem, (size_t)bnsize-r_rem); p += bnsize-r_rem; memmove(p, mid, (size_t)mid_len-1); p += mid_len-1; *p = (uint8_t)(bnsize + s_high - s_rem); p += 1; if(s_high) { *p = 0; p += 1; } memmove(p, d+bnsize+s_rem, (size_t)bnsize-s_rem); *len = (unsigned int)raw_sig_len; return 1; } #endif /* USE_ECDSA */ #ifdef USE_ECDSA_EVP_WORKAROUND static EVP_MD ecdsa_evp_256_md; static EVP_MD ecdsa_evp_384_md; void ecdsa_evp_workaround_init(void) { /* openssl before 1.0.0 fixes RSA with the SHA256 * hash in EVP. We create one for ecdsa_sha256 */ ecdsa_evp_256_md = *EVP_sha256(); ecdsa_evp_256_md.required_pkey_type[0] = EVP_PKEY_EC; ecdsa_evp_256_md.verify = (void*)ECDSA_verify; ecdsa_evp_384_md = *EVP_sha384(); ecdsa_evp_384_md.required_pkey_type[0] = EVP_PKEY_EC; ecdsa_evp_384_md.verify = (void*)ECDSA_verify; } #endif /* USE_ECDSA_EVP_WORKAROUND */ /** * Setup key and digest for verification. Adjust sig if necessary. * * @param algo: key algorithm * @param evp_key: EVP PKEY public key to create. * @param digest_type: digest type to use * @param key: key to setup for. * @param keylen: length of key. * @return false on failure. */ static int setup_key_digest(int algo, EVP_PKEY** evp_key, const EVP_MD** digest_type, unsigned char* key, size_t keylen) { #if defined(USE_DSA) && defined(USE_SHA1) DSA* dsa; #endif RSA* rsa; switch(algo) { #if defined(USE_DSA) && defined(USE_SHA1) case LDNS_DSA: case LDNS_DSA_NSEC3: *evp_key = EVP_PKEY_new(); if(!*evp_key) { log_err("verify: malloc failure in crypto"); return 0; } dsa = sldns_key_buf2dsa_raw(key, keylen); if(!dsa) { verbose(VERB_QUERY, "verify: " "sldns_key_buf2dsa_raw failed"); return 0; } if(EVP_PKEY_assign_DSA(*evp_key, dsa) == 0) { verbose(VERB_QUERY, "verify: " "EVP_PKEY_assign_DSA failed"); return 0; } #ifdef HAVE_EVP_DSS1 *digest_type = EVP_dss1(); #else *digest_type = EVP_sha1(); #endif break; #endif /* USE_DSA && USE_SHA1 */ #if defined(USE_SHA1) || (defined(HAVE_EVP_SHA256) && defined(USE_SHA2)) || (defined(HAVE_EVP_SHA512) && defined(USE_SHA2)) #ifdef USE_SHA1 case LDNS_RSASHA1: case LDNS_RSASHA1_NSEC3: #endif #if defined(HAVE_EVP_SHA256) && defined(USE_SHA2) case LDNS_RSASHA256: #endif #if defined(HAVE_EVP_SHA512) && defined(USE_SHA2) case LDNS_RSASHA512: #endif *evp_key = EVP_PKEY_new(); if(!*evp_key) { log_err("verify: malloc failure in crypto"); return 0; } rsa = sldns_key_buf2rsa_raw(key, keylen); if(!rsa) { verbose(VERB_QUERY, "verify: " "sldns_key_buf2rsa_raw SHA failed"); return 0; } if(EVP_PKEY_assign_RSA(*evp_key, rsa) == 0) { verbose(VERB_QUERY, "verify: " "EVP_PKEY_assign_RSA SHA failed"); return 0; } /* select SHA version */ #if defined(HAVE_EVP_SHA256) && defined(USE_SHA2) if(algo == LDNS_RSASHA256) *digest_type = EVP_sha256(); else #endif #if defined(HAVE_EVP_SHA512) && defined(USE_SHA2) if(algo == LDNS_RSASHA512) *digest_type = EVP_sha512(); else #endif #ifdef USE_SHA1 *digest_type = EVP_sha1(); #else { verbose(VERB_QUERY, "no digest available"); return 0; } #endif break; #endif /* defined(USE_SHA1) || (defined(HAVE_EVP_SHA256) && defined(USE_SHA2)) || (defined(HAVE_EVP_SHA512) && defined(USE_SHA2)) */ case LDNS_RSAMD5: *evp_key = EVP_PKEY_new(); if(!*evp_key) { log_err("verify: malloc failure in crypto"); return 0; } rsa = sldns_key_buf2rsa_raw(key, keylen); if(!rsa) { verbose(VERB_QUERY, "verify: " "sldns_key_buf2rsa_raw MD5 failed"); return 0; } if(EVP_PKEY_assign_RSA(*evp_key, rsa) == 0) { verbose(VERB_QUERY, "verify: " "EVP_PKEY_assign_RSA MD5 failed"); return 0; } *digest_type = EVP_md5(); break; #ifdef USE_GOST case LDNS_ECC_GOST: *evp_key = sldns_gost2pkey_raw(key, keylen); if(!*evp_key) { verbose(VERB_QUERY, "verify: " "sldns_gost2pkey_raw failed"); return 0; } *digest_type = EVP_get_digestbyname("md_gost94"); if(!*digest_type) { verbose(VERB_QUERY, "verify: " "EVP_getdigest md_gost94 failed"); return 0; } break; #endif #ifdef USE_ECDSA case LDNS_ECDSAP256SHA256: *evp_key = sldns_ecdsa2pkey_raw(key, keylen, LDNS_ECDSAP256SHA256); if(!*evp_key) { verbose(VERB_QUERY, "verify: " "sldns_ecdsa2pkey_raw failed"); return 0; } #ifdef USE_ECDSA_EVP_WORKAROUND *digest_type = &ecdsa_evp_256_md; #else *digest_type = EVP_sha256(); #endif break; case LDNS_ECDSAP384SHA384: *evp_key = sldns_ecdsa2pkey_raw(key, keylen, LDNS_ECDSAP384SHA384); if(!*evp_key) { verbose(VERB_QUERY, "verify: " "sldns_ecdsa2pkey_raw failed"); return 0; } #ifdef USE_ECDSA_EVP_WORKAROUND *digest_type = &ecdsa_evp_384_md; #else *digest_type = EVP_sha384(); #endif break; #endif /* USE_ECDSA */ #ifdef USE_ED25519 case LDNS_ED25519: *evp_key = sldns_ed255192pkey_raw(key, keylen); if(!*evp_key) { verbose(VERB_QUERY, "verify: " "sldns_ed255192pkey_raw failed"); return 0; } *digest_type = NULL; break; #endif /* USE_ED25519 */ #ifdef USE_ED448 case LDNS_ED448: *evp_key = sldns_ed4482pkey_raw(key, keylen); if(!*evp_key) { verbose(VERB_QUERY, "verify: " "sldns_ed4482pkey_raw failed"); return 0; } *digest_type = NULL; break; #endif /* USE_ED448 */ default: verbose(VERB_QUERY, "verify: unknown algorithm %d", algo); return 0; } return 1; } /** * Check a canonical sig+rrset and signature against a dnskey * @param buf: buffer with data to verify, the first rrsig part and the * canonicalized rrset. * @param algo: DNSKEY algorithm. * @param sigblock: signature rdata field from RRSIG * @param sigblock_len: length of sigblock data. * @param key: public key data from DNSKEY RR. * @param keylen: length of keydata. * @param reason: bogus reason in more detail. * @return secure if verification succeeded, bogus on crypto failure, * unchecked on format errors and alloc failures. */ enum sec_status verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock, unsigned int sigblock_len, unsigned char* key, unsigned int keylen, char** reason) { const EVP_MD *digest_type; EVP_MD_CTX* ctx; int res, dofree = 0, docrypto_free = 0; EVP_PKEY *evp_key = NULL; #ifndef USE_DSA if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3) &&(fake_dsa||fake_sha1)) return sec_status_secure; #endif #ifndef USE_SHA1 if(fake_sha1 && (algo == LDNS_DSA || algo == LDNS_DSA_NSEC3 || algo == LDNS_RSASHA1 || algo == LDNS_RSASHA1_NSEC3)) return sec_status_secure; #endif if(!setup_key_digest(algo, &evp_key, &digest_type, key, keylen)) { verbose(VERB_QUERY, "verify: failed to setup key"); *reason = "use of key for crypto failed"; EVP_PKEY_free(evp_key); return sec_status_bogus; } #ifdef USE_DSA /* if it is a DSA signature in bind format, convert to DER format */ if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3) && sigblock_len == 1+2*SHA_DIGEST_LENGTH) { if(!setup_dsa_sig(&sigblock, &sigblock_len)) { verbose(VERB_QUERY, "verify: failed to setup DSA sig"); *reason = "use of key for DSA crypto failed"; EVP_PKEY_free(evp_key); return sec_status_bogus; } docrypto_free = 1; } #endif #if defined(USE_ECDSA) && defined(USE_DSA) else #endif #ifdef USE_ECDSA if(algo == LDNS_ECDSAP256SHA256 || algo == LDNS_ECDSAP384SHA384) { /* EVP uses ASN prefix on sig, which is not in the wire data */ if(!setup_ecdsa_sig(&sigblock, &sigblock_len)) { verbose(VERB_QUERY, "verify: failed to setup ECDSA sig"); *reason = "use of signature for ECDSA crypto failed"; EVP_PKEY_free(evp_key); return sec_status_bogus; } dofree = 1; } #endif /* USE_ECDSA */ /* do the signature cryptography work */ #ifdef HAVE_EVP_MD_CTX_NEW ctx = EVP_MD_CTX_new(); #else ctx = (EVP_MD_CTX*)malloc(sizeof(*ctx)); if(ctx) EVP_MD_CTX_init(ctx); #endif if(!ctx) { log_err("EVP_MD_CTX_new: malloc failure"); EVP_PKEY_free(evp_key); if(dofree) free(sigblock); else if(docrypto_free) OPENSSL_free(sigblock); return sec_status_unchecked; } #ifndef HAVE_EVP_DIGESTVERIFY if(EVP_DigestInit(ctx, digest_type) == 0) { verbose(VERB_QUERY, "verify: EVP_DigestInit failed"); #ifdef HAVE_EVP_MD_CTX_NEW EVP_MD_CTX_destroy(ctx); #else EVP_MD_CTX_cleanup(ctx); free(ctx); #endif EVP_PKEY_free(evp_key); if(dofree) free(sigblock); else if(docrypto_free) OPENSSL_free(sigblock); return sec_status_unchecked; } if(EVP_DigestUpdate(ctx, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf)) == 0) { verbose(VERB_QUERY, "verify: EVP_DigestUpdate failed"); #ifdef HAVE_EVP_MD_CTX_NEW EVP_MD_CTX_destroy(ctx); #else EVP_MD_CTX_cleanup(ctx); free(ctx); #endif EVP_PKEY_free(evp_key); if(dofree) free(sigblock); else if(docrypto_free) OPENSSL_free(sigblock); return sec_status_unchecked; } res = EVP_VerifyFinal(ctx, sigblock, sigblock_len, evp_key); #else /* HAVE_EVP_DIGESTVERIFY */ if(EVP_DigestVerifyInit(ctx, NULL, digest_type, NULL, evp_key) == 0) { verbose(VERB_QUERY, "verify: EVP_DigestVerifyInit failed"); #ifdef HAVE_EVP_MD_CTX_NEW EVP_MD_CTX_destroy(ctx); #else EVP_MD_CTX_cleanup(ctx); free(ctx); #endif EVP_PKEY_free(evp_key); if(dofree) free(sigblock); else if(docrypto_free) OPENSSL_free(sigblock); return sec_status_unchecked; } res = EVP_DigestVerify(ctx, sigblock, sigblock_len, (unsigned char*)sldns_buffer_begin(buf), sldns_buffer_limit(buf)); #endif #ifdef HAVE_EVP_MD_CTX_NEW EVP_MD_CTX_destroy(ctx); #else EVP_MD_CTX_cleanup(ctx); free(ctx); #endif EVP_PKEY_free(evp_key); if(dofree) free(sigblock); else if(docrypto_free) OPENSSL_free(sigblock); if(res == 1) { return sec_status_secure; } else if(res == 0) { verbose(VERB_QUERY, "verify: signature mismatch"); *reason = "signature crypto failed"; return sec_status_bogus; } log_crypto_error("verify:", ERR_get_error()); return sec_status_unchecked; } /**************************************************/ #elif defined(HAVE_NSS) /* libnss implementation */ /* nss3 */ #include "sechash.h" #include "pk11pub.h" #include "keyhi.h" #include "secerr.h" #include "cryptohi.h" /* nspr4 */ #include "prerror.h" /* return size of digest if supported, or 0 otherwise */ size_t nsec3_hash_algo_size_supported(int id) { switch(id) { case NSEC3_HASH_SHA1: return SHA1_LENGTH; default: return 0; } } /* perform nsec3 hash. return false on failure */ int secalgo_nsec3_hash(int algo, unsigned char* buf, size_t len, unsigned char* res) { switch(algo) { case NSEC3_HASH_SHA1: (void)HASH_HashBuf(HASH_AlgSHA1, res, buf, (unsigned long)len); return 1; default: return 0; } } void secalgo_hash_sha256(unsigned char* buf, size_t len, unsigned char* res) { (void)HASH_HashBuf(HASH_AlgSHA256, res, buf, (unsigned long)len); } size_t ds_digest_size_supported(int algo) { /* uses libNSS */ switch(algo) { #ifdef USE_SHA1 case LDNS_SHA1: return SHA1_LENGTH; #endif #ifdef USE_SHA2 case LDNS_SHA256: return SHA256_LENGTH; #endif #ifdef USE_ECDSA case LDNS_SHA384: return SHA384_LENGTH; #endif /* GOST not supported in NSS */ case LDNS_HASH_GOST: default: break; } return 0; } int secalgo_ds_digest(int algo, unsigned char* buf, size_t len, unsigned char* res) { /* uses libNSS */ switch(algo) { #ifdef USE_SHA1 case LDNS_SHA1: return HASH_HashBuf(HASH_AlgSHA1, res, buf, len) == SECSuccess; #endif #if defined(USE_SHA2) case LDNS_SHA256: return HASH_HashBuf(HASH_AlgSHA256, res, buf, len) == SECSuccess; #endif #ifdef USE_ECDSA case LDNS_SHA384: return HASH_HashBuf(HASH_AlgSHA384, res, buf, len) == SECSuccess; #endif case LDNS_HASH_GOST: default: verbose(VERB_QUERY, "unknown DS digest algorithm %d", algo); break; } return 0; } int dnskey_algo_id_is_supported(int id) { /* uses libNSS */ switch(id) { case LDNS_RSAMD5: /* RFC 6725 deprecates RSAMD5 */ return 0; #if defined(USE_SHA1) || defined(USE_SHA2) #if defined(USE_DSA) && defined(USE_SHA1) case LDNS_DSA: case LDNS_DSA_NSEC3: #endif #ifdef USE_SHA1 case LDNS_RSASHA1: case LDNS_RSASHA1_NSEC3: #endif #ifdef USE_SHA2 case LDNS_RSASHA256: #endif #ifdef USE_SHA2 case LDNS_RSASHA512: #endif return 1; #endif /* SHA1 or SHA2 */ #ifdef USE_ECDSA case LDNS_ECDSAP256SHA256: case LDNS_ECDSAP384SHA384: return PK11_TokenExists(CKM_ECDSA); #endif case LDNS_ECC_GOST: default: return 0; } } /* return a new public key for NSS */ static SECKEYPublicKey* nss_key_create(KeyType ktype) { SECKEYPublicKey* key; PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if(!arena) { log_err("out of memory, PORT_NewArena failed"); return NULL; } key = PORT_ArenaZNew(arena, SECKEYPublicKey); if(!key) { log_err("out of memory, PORT_ArenaZNew failed"); PORT_FreeArena(arena, PR_FALSE); return NULL; } key->arena = arena; key->keyType = ktype; key->pkcs11Slot = NULL; key->pkcs11ID = CK_INVALID_HANDLE; return key; } static SECKEYPublicKey* nss_buf2ecdsa(unsigned char* key, size_t len, int algo) { SECKEYPublicKey* pk; SECItem pub = {siBuffer, NULL, 0}; SECItem params = {siBuffer, NULL, 0}; static unsigned char param256[] = { /* OBJECTIDENTIFIER 1.2.840.10045.3.1.7 (P-256) * {iso(1) member-body(2) us(840) ansi-x962(10045) curves(3) prime(1) prime256v1(7)} */ 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07 }; static unsigned char param384[] = { /* OBJECTIDENTIFIER 1.3.132.0.34 (P-384) * {iso(1) identified-organization(3) certicom(132) curve(0) ansip384r1(34)} */ 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22 }; unsigned char buf[256+2]; /* sufficient for 2*384/8+1 */ /* check length, which uncompressed must be 2 bignums */ if(algo == LDNS_ECDSAP256SHA256) { if(len != 2*256/8) return NULL; /* ECCurve_X9_62_PRIME_256V1 */ } else if(algo == LDNS_ECDSAP384SHA384) { if(len != 2*384/8) return NULL; /* ECCurve_X9_62_PRIME_384R1 */ } else return NULL; buf[0] = 0x04; /* POINT_FORM_UNCOMPRESSED */ memmove(buf+1, key, len); pub.data = buf; pub.len = len+1; if(algo == LDNS_ECDSAP256SHA256) { params.data = param256; params.len = sizeof(param256); } else { params.data = param384; params.len = sizeof(param384); } pk = nss_key_create(ecKey); if(!pk) return NULL; pk->u.ec.size = (len/2)*8; if(SECITEM_CopyItem(pk->arena, &pk->u.ec.publicValue, &pub)) { SECKEY_DestroyPublicKey(pk); return NULL; } if(SECITEM_CopyItem(pk->arena, &pk->u.ec.DEREncodedParams, ¶ms)) { SECKEY_DestroyPublicKey(pk); return NULL; } return pk; } static SECKEYPublicKey* nss_buf2dsa(unsigned char* key, size_t len) { SECKEYPublicKey* pk; uint8_t T; uint16_t length; uint16_t offset; SECItem Q = {siBuffer, NULL, 0}; SECItem P = {siBuffer, NULL, 0}; SECItem G = {siBuffer, NULL, 0}; SECItem Y = {siBuffer, NULL, 0}; if(len == 0) return NULL; T = (uint8_t)key[0]; length = (64 + T * 8); offset = 1; if (T > 8) { return NULL; } if(len < (size_t)1 + SHA1_LENGTH + 3*length) return NULL; Q.data = key+offset; Q.len = SHA1_LENGTH; offset += SHA1_LENGTH; P.data = key+offset; P.len = length; offset += length; G.data = key+offset; G.len = length; offset += length; Y.data = key+offset; Y.len = length; offset += length; pk = nss_key_create(dsaKey); if(!pk) return NULL; if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.params.prime, &P)) { SECKEY_DestroyPublicKey(pk); return NULL; } if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.params.subPrime, &Q)) { SECKEY_DestroyPublicKey(pk); return NULL; } if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.params.base, &G)) { SECKEY_DestroyPublicKey(pk); return NULL; } if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.publicValue, &Y)) { SECKEY_DestroyPublicKey(pk); return NULL; } return pk; } static SECKEYPublicKey* nss_buf2rsa(unsigned char* key, size_t len) { SECKEYPublicKey* pk; uint16_t exp; uint16_t offset; uint16_t int16; SECItem modulus = {siBuffer, NULL, 0}; SECItem exponent = {siBuffer, NULL, 0}; if(len == 0) return NULL; if(key[0] == 0) { if(len < 3) return NULL; /* the exponent is too large so it's places further */ memmove(&int16, key+1, 2); exp = ntohs(int16); offset = 3; } else { exp = key[0]; offset = 1; } /* key length at least one */ if(len < (size_t)offset + exp + 1) return NULL; exponent.data = key+offset; exponent.len = exp; offset += exp; modulus.data = key+offset; modulus.len = (len - offset); pk = nss_key_create(rsaKey); if(!pk) return NULL; if(SECITEM_CopyItem(pk->arena, &pk->u.rsa.modulus, &modulus)) { SECKEY_DestroyPublicKey(pk); return NULL; } if(SECITEM_CopyItem(pk->arena, &pk->u.rsa.publicExponent, &exponent)) { SECKEY_DestroyPublicKey(pk); return NULL; } return pk; } /** * Setup key and digest for verification. Adjust sig if necessary. * * @param algo: key algorithm * @param evp_key: EVP PKEY public key to create. * @param digest_type: digest type to use * @param key: key to setup for. * @param keylen: length of key. * @param prefix: if returned, the ASN prefix for the hashblob. * @param prefixlen: length of the prefix. * @return false on failure. */ static int nss_setup_key_digest(int algo, SECKEYPublicKey** pubkey, HASH_HashType* htype, unsigned char* key, size_t keylen, unsigned char** prefix, size_t* prefixlen) { /* uses libNSS */ /* hash prefix for md5, RFC2537 */ static unsigned char p_md5[] = {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10}; /* hash prefix to prepend to hash output, from RFC3110 */ static unsigned char p_sha1[] = {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14}; /* from RFC5702 */ static unsigned char p_sha256[] = {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20}; static unsigned char p_sha512[] = {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40}; /* from RFC6234 */ /* for future RSASHA384 .. static unsigned char p_sha384[] = {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30}; */ switch(algo) { #if defined(USE_SHA1) || defined(USE_SHA2) #if defined(USE_DSA) && defined(USE_SHA1) case LDNS_DSA: case LDNS_DSA_NSEC3: *pubkey = nss_buf2dsa(key, keylen); if(!*pubkey) { log_err("verify: malloc failure in crypto"); return 0; } *htype = HASH_AlgSHA1; /* no prefix for DSA verification */ break; #endif #ifdef USE_SHA1 case LDNS_RSASHA1: case LDNS_RSASHA1_NSEC3: #endif #ifdef USE_SHA2 case LDNS_RSASHA256: #endif #ifdef USE_SHA2 case LDNS_RSASHA512: #endif *pubkey = nss_buf2rsa(key, keylen); if(!*pubkey) { log_err("verify: malloc failure in crypto"); return 0; } /* select SHA version */ #ifdef USE_SHA2 if(algo == LDNS_RSASHA256) { *htype = HASH_AlgSHA256; *prefix = p_sha256; *prefixlen = sizeof(p_sha256); } else #endif #ifdef USE_SHA2 if(algo == LDNS_RSASHA512) { *htype = HASH_AlgSHA512; *prefix = p_sha512; *prefixlen = sizeof(p_sha512); } else #endif #ifdef USE_SHA1 { *htype = HASH_AlgSHA1; *prefix = p_sha1; *prefixlen = sizeof(p_sha1); } #else { verbose(VERB_QUERY, "verify: no digest algo"); return 0; } #endif break; #endif /* SHA1 or SHA2 */ case LDNS_RSAMD5: *pubkey = nss_buf2rsa(key, keylen); if(!*pubkey) { log_err("verify: malloc failure in crypto"); return 0; } *htype = HASH_AlgMD5; *prefix = p_md5; *prefixlen = sizeof(p_md5); break; #ifdef USE_ECDSA case LDNS_ECDSAP256SHA256: *pubkey = nss_buf2ecdsa(key, keylen, LDNS_ECDSAP256SHA256); if(!*pubkey) { log_err("verify: malloc failure in crypto"); return 0; } *htype = HASH_AlgSHA256; /* no prefix for DSA verification */ break; case LDNS_ECDSAP384SHA384: *pubkey = nss_buf2ecdsa(key, keylen, LDNS_ECDSAP384SHA384); if(!*pubkey) { log_err("verify: malloc failure in crypto"); return 0; } *htype = HASH_AlgSHA384; /* no prefix for DSA verification */ break; #endif /* USE_ECDSA */ case LDNS_ECC_GOST: default: verbose(VERB_QUERY, "verify: unknown algorithm %d", algo); return 0; } return 1; } /** * Check a canonical sig+rrset and signature against a dnskey * @param buf: buffer with data to verify, the first rrsig part and the * canonicalized rrset. * @param algo: DNSKEY algorithm. * @param sigblock: signature rdata field from RRSIG * @param sigblock_len: length of sigblock data. * @param key: public key data from DNSKEY RR. * @param keylen: length of keydata. * @param reason: bogus reason in more detail. * @return secure if verification succeeded, bogus on crypto failure, * unchecked on format errors and alloc failures. */ enum sec_status verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock, unsigned int sigblock_len, unsigned char* key, unsigned int keylen, char** reason) { /* uses libNSS */ /* large enough for the different hashes */ unsigned char hash[HASH_LENGTH_MAX]; unsigned char hash2[HASH_LENGTH_MAX*2]; HASH_HashType htype = 0; SECKEYPublicKey* pubkey = NULL; SECItem secsig = {siBuffer, sigblock, sigblock_len}; SECItem sechash = {siBuffer, hash, 0}; SECStatus res; unsigned char* prefix = NULL; /* prefix for hash, RFC3110, RFC5702 */ size_t prefixlen = 0; int err; if(!nss_setup_key_digest(algo, &pubkey, &htype, key, keylen, &prefix, &prefixlen)) { verbose(VERB_QUERY, "verify: failed to setup key"); *reason = "use of key for crypto failed"; SECKEY_DestroyPublicKey(pubkey); return sec_status_bogus; } #if defined(USE_DSA) && defined(USE_SHA1) /* need to convert DSA, ECDSA signatures? */ if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3)) { if(sigblock_len == 1+2*SHA1_LENGTH) { secsig.data ++; secsig.len --; } else { SECItem* p = DSAU_DecodeDerSig(&secsig); if(!p) { verbose(VERB_QUERY, "verify: failed DER decode"); *reason = "signature DER decode failed"; SECKEY_DestroyPublicKey(pubkey); return sec_status_bogus; } if(SECITEM_CopyItem(pubkey->arena, &secsig, p)) { log_err("alloc failure in DER decode"); SECKEY_DestroyPublicKey(pubkey); SECITEM_FreeItem(p, PR_TRUE); return sec_status_unchecked; } SECITEM_FreeItem(p, PR_TRUE); } } #endif /* USE_DSA */ /* do the signature cryptography work */ /* hash the data */ sechash.len = HASH_ResultLen(htype); if(sechash.len > sizeof(hash)) { verbose(VERB_QUERY, "verify: hash too large for buffer"); SECKEY_DestroyPublicKey(pubkey); return sec_status_unchecked; } if(HASH_HashBuf(htype, hash, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf)) != SECSuccess) { verbose(VERB_QUERY, "verify: HASH_HashBuf failed"); SECKEY_DestroyPublicKey(pubkey); return sec_status_unchecked; } if(prefix) { int hashlen = sechash.len; if(prefixlen+hashlen > sizeof(hash2)) { verbose(VERB_QUERY, "verify: hashprefix too large"); SECKEY_DestroyPublicKey(pubkey); return sec_status_unchecked; } sechash.data = hash2; sechash.len = prefixlen+hashlen; memcpy(sechash.data, prefix, prefixlen); memmove(sechash.data+prefixlen, hash, hashlen); } /* verify the signature */ res = PK11_Verify(pubkey, &secsig, &sechash, NULL /*wincx*/); SECKEY_DestroyPublicKey(pubkey); if(res == SECSuccess) { return sec_status_secure; } err = PORT_GetError(); if(err != SEC_ERROR_BAD_SIGNATURE) { /* failed to verify */ verbose(VERB_QUERY, "verify: PK11_Verify failed: %s", PORT_ErrorToString(err)); /* if it is not supported, like ECC is removed, we get, * SEC_ERROR_NO_MODULE */ if(err == SEC_ERROR_NO_MODULE) return sec_status_unchecked; /* but other errors are commonly returned * for a bad signature from NSS. Thus we return bogus, * not unchecked */ *reason = "signature crypto failed"; return sec_status_bogus; } verbose(VERB_QUERY, "verify: signature mismatch: %s", PORT_ErrorToString(err)); *reason = "signature crypto failed"; return sec_status_bogus; } #elif defined(HAVE_NETTLE) #include "sha.h" #include "bignum.h" #include "macros.h" #include "rsa.h" #include "dsa.h" #ifdef HAVE_NETTLE_DSA_COMPAT_H #include "dsa-compat.h" #endif #include "asn1.h" #ifdef USE_ECDSA #include "ecdsa.h" #include "ecc-curve.h" #endif #ifdef HAVE_NETTLE_EDDSA_H #include "eddsa.h" #endif static int _digest_nettle(int algo, uint8_t* buf, size_t len, unsigned char* res) { switch(algo) { case SHA1_DIGEST_SIZE: { struct sha1_ctx ctx; sha1_init(&ctx); sha1_update(&ctx, len, buf); sha1_digest(&ctx, SHA1_DIGEST_SIZE, res); return 1; } case SHA256_DIGEST_SIZE: { struct sha256_ctx ctx; sha256_init(&ctx); sha256_update(&ctx, len, buf); sha256_digest(&ctx, SHA256_DIGEST_SIZE, res); return 1; } case SHA384_DIGEST_SIZE: { struct sha384_ctx ctx; sha384_init(&ctx); sha384_update(&ctx, len, buf); sha384_digest(&ctx, SHA384_DIGEST_SIZE, res); return 1; } case SHA512_DIGEST_SIZE: { struct sha512_ctx ctx; sha512_init(&ctx); sha512_update(&ctx, len, buf); sha512_digest(&ctx, SHA512_DIGEST_SIZE, res); return 1; } default: break; } return 0; } /* return size of digest if supported, or 0 otherwise */ size_t nsec3_hash_algo_size_supported(int id) { switch(id) { case NSEC3_HASH_SHA1: return SHA1_DIGEST_SIZE; default: return 0; } } /* perform nsec3 hash. return false on failure */ int secalgo_nsec3_hash(int algo, unsigned char* buf, size_t len, unsigned char* res) { switch(algo) { case NSEC3_HASH_SHA1: return _digest_nettle(SHA1_DIGEST_SIZE, (uint8_t*)buf, len, res); default: return 0; } } void secalgo_hash_sha256(unsigned char* buf, size_t len, unsigned char* res) { _digest_nettle(SHA256_DIGEST_SIZE, (uint8_t*)buf, len, res); } /** * Return size of DS digest according to its hash algorithm. * @param algo: DS digest algo. * @return size in bytes of digest, or 0 if not supported. */ size_t ds_digest_size_supported(int algo) { switch(algo) { case LDNS_SHA1: #ifdef USE_SHA1 return SHA1_DIGEST_SIZE; #else if(fake_sha1) return 20; return 0; #endif #ifdef USE_SHA2 case LDNS_SHA256: return SHA256_DIGEST_SIZE; #endif #ifdef USE_ECDSA case LDNS_SHA384: return SHA384_DIGEST_SIZE; #endif /* GOST not supported */ case LDNS_HASH_GOST: default: break; } return 0; } int secalgo_ds_digest(int algo, unsigned char* buf, size_t len, unsigned char* res) { switch(algo) { #ifdef USE_SHA1 case LDNS_SHA1: return _digest_nettle(SHA1_DIGEST_SIZE, buf, len, res); #endif #if defined(USE_SHA2) case LDNS_SHA256: return _digest_nettle(SHA256_DIGEST_SIZE, buf, len, res); #endif #ifdef USE_ECDSA case LDNS_SHA384: return _digest_nettle(SHA384_DIGEST_SIZE, buf, len, res); #endif case LDNS_HASH_GOST: default: verbose(VERB_QUERY, "unknown DS digest algorithm %d", algo); break; } return 0; } int dnskey_algo_id_is_supported(int id) { /* uses libnettle */ switch(id) { #if defined(USE_DSA) && defined(USE_SHA1) case LDNS_DSA: case LDNS_DSA_NSEC3: #endif #ifdef USE_SHA1 case LDNS_RSASHA1: case LDNS_RSASHA1_NSEC3: #endif #ifdef USE_SHA2 case LDNS_RSASHA256: case LDNS_RSASHA512: #endif #ifdef USE_ECDSA case LDNS_ECDSAP256SHA256: case LDNS_ECDSAP384SHA384: #endif return 1; #ifdef USE_ED25519 case LDNS_ED25519: return 1; #endif case LDNS_RSAMD5: /* RFC 6725 deprecates RSAMD5 */ case LDNS_ECC_GOST: default: return 0; } } #if defined(USE_DSA) && defined(USE_SHA1) static char * _verify_nettle_dsa(sldns_buffer* buf, unsigned char* sigblock, unsigned int sigblock_len, unsigned char* key, unsigned int keylen) { uint8_t digest[SHA1_DIGEST_SIZE]; uint8_t key_t_value; int res = 0; size_t offset; struct dsa_public_key pubkey; struct dsa_signature signature; unsigned int expected_len; /* Extract DSA signature from the record */ nettle_dsa_signature_init(&signature); /* Signature length: 41 bytes - RFC 2536 sec. 3 */ if(sigblock_len == 41) { if(key[0] != sigblock[0]) return "invalid T value in DSA signature or pubkey"; nettle_mpz_set_str_256_u(signature.r, 20, sigblock+1); nettle_mpz_set_str_256_u(signature.s, 20, sigblock+1+20); } else { /* DER encoded, decode the ASN1 notated R and S bignums */ /* SEQUENCE { r INTEGER, s INTEGER } */ struct asn1_der_iterator i, seq; if(asn1_der_iterator_first(&i, sigblock_len, (uint8_t*)sigblock) != ASN1_ITERATOR_CONSTRUCTED || i.type != ASN1_SEQUENCE) return "malformed DER encoded DSA signature"; /* decode this element of i using the seq iterator */ if(asn1_der_decode_constructed(&i, &seq) != ASN1_ITERATOR_PRIMITIVE || seq.type != ASN1_INTEGER) return "malformed DER encoded DSA signature"; if(!asn1_der_get_bignum(&seq, signature.r, 20*8)) return "malformed DER encoded DSA signature"; if(asn1_der_iterator_next(&seq) != ASN1_ITERATOR_PRIMITIVE || seq.type != ASN1_INTEGER) return "malformed DER encoded DSA signature"; if(!asn1_der_get_bignum(&seq, signature.s, 20*8)) return "malformed DER encoded DSA signature"; if(asn1_der_iterator_next(&i) != ASN1_ITERATOR_END) return "malformed DER encoded DSA signature"; } /* Validate T values constraints - RFC 2536 sec. 2 & sec. 3 */ key_t_value = key[0]; if (key_t_value > 8) { return "invalid T value in DSA pubkey"; } /* Pubkey minimum length: 21 bytes - RFC 2536 sec. 2 */ if (keylen < 21) { return "DSA pubkey too short"; } expected_len = 1 + /* T */ 20 + /* Q */ (64 + key_t_value*8) + /* P */ (64 + key_t_value*8) + /* G */ (64 + key_t_value*8); /* Y */ if (keylen != expected_len ) { return "invalid DSA pubkey length"; } /* Extract DSA pubkey from the record */ nettle_dsa_public_key_init(&pubkey); offset = 1; nettle_mpz_set_str_256_u(pubkey.q, 20, key+offset); offset += 20; nettle_mpz_set_str_256_u(pubkey.p, (64 + key_t_value*8), key+offset); offset += (64 + key_t_value*8); nettle_mpz_set_str_256_u(pubkey.g, (64 + key_t_value*8), key+offset); offset += (64 + key_t_value*8); nettle_mpz_set_str_256_u(pubkey.y, (64 + key_t_value*8), key+offset); /* Digest content of "buf" and verify its DSA signature in "sigblock"*/ res = _digest_nettle(SHA1_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest); res &= dsa_sha1_verify_digest(&pubkey, digest, &signature); /* Clear and return */ nettle_dsa_signature_clear(&signature); nettle_dsa_public_key_clear(&pubkey); if (!res) return "DSA signature verification failed"; else return NULL; } #endif /* USE_DSA */ static char * _verify_nettle_rsa(sldns_buffer* buf, unsigned int digest_size, char* sigblock, unsigned int sigblock_len, uint8_t* key, unsigned int keylen) { uint16_t exp_len = 0; size_t exp_offset = 0, mod_offset = 0; struct rsa_public_key pubkey; mpz_t signature; int res = 0; /* RSA pubkey parsing as per RFC 3110 sec. 2 */ if( keylen <= 1) { return "null RSA key"; } if (key[0] != 0) { /* 1-byte length */ exp_len = key[0]; exp_offset = 1; } else { /* 1-byte NUL + 2-bytes exponent length */ if (keylen < 3) { return "incorrect RSA key length"; } exp_len = READ_UINT16(key+1); if (exp_len == 0) return "null RSA exponent length"; exp_offset = 3; } /* Check that we are not over-running input length */ if (keylen < exp_offset + exp_len + 1) { return "RSA key content shorter than expected"; } mod_offset = exp_offset + exp_len; nettle_rsa_public_key_init(&pubkey); pubkey.size = keylen - mod_offset; nettle_mpz_set_str_256_u(pubkey.e, exp_len, &key[exp_offset]); nettle_mpz_set_str_256_u(pubkey.n, pubkey.size, &key[mod_offset]); /* Digest content of "buf" and verify its RSA signature in "sigblock"*/ nettle_mpz_init_set_str_256_u(signature, sigblock_len, (uint8_t*)sigblock); switch (digest_size) { case SHA1_DIGEST_SIZE: { uint8_t digest[SHA1_DIGEST_SIZE]; res = _digest_nettle(SHA1_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest); res &= rsa_sha1_verify_digest(&pubkey, digest, signature); break; } case SHA256_DIGEST_SIZE: { uint8_t digest[SHA256_DIGEST_SIZE]; res = _digest_nettle(SHA256_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest); res &= rsa_sha256_verify_digest(&pubkey, digest, signature); break; } case SHA512_DIGEST_SIZE: { uint8_t digest[SHA512_DIGEST_SIZE]; res = _digest_nettle(SHA512_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest); res &= rsa_sha512_verify_digest(&pubkey, digest, signature); break; } default: break; } /* Clear and return */ nettle_rsa_public_key_clear(&pubkey); mpz_clear(signature); if (!res) { return "RSA signature verification failed"; } else { return NULL; } } #ifdef USE_ECDSA static char * _verify_nettle_ecdsa(sldns_buffer* buf, unsigned int digest_size, unsigned char* sigblock, unsigned int sigblock_len, unsigned char* key, unsigned int keylen) { int res = 0; struct ecc_point pubkey; struct dsa_signature signature; /* Always matched strength, as per RFC 6605 sec. 1 */ if (sigblock_len != 2*digest_size || keylen != 2*digest_size) { return "wrong ECDSA signature length"; } /* Parse ECDSA signature as per RFC 6605 sec. 4 */ nettle_dsa_signature_init(&signature); switch (digest_size) { case SHA256_DIGEST_SIZE: { uint8_t digest[SHA256_DIGEST_SIZE]; mpz_t x, y; nettle_ecc_point_init(&pubkey, &nettle_secp_256r1); nettle_mpz_init_set_str_256_u(x, SHA256_DIGEST_SIZE, key); nettle_mpz_init_set_str_256_u(y, SHA256_DIGEST_SIZE, key+SHA256_DIGEST_SIZE); nettle_mpz_set_str_256_u(signature.r, SHA256_DIGEST_SIZE, sigblock); nettle_mpz_set_str_256_u(signature.s, SHA256_DIGEST_SIZE, sigblock+SHA256_DIGEST_SIZE); res = _digest_nettle(SHA256_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest); res &= nettle_ecc_point_set(&pubkey, x, y); res &= nettle_ecdsa_verify (&pubkey, SHA256_DIGEST_SIZE, digest, &signature); mpz_clear(x); mpz_clear(y); break; } case SHA384_DIGEST_SIZE: { uint8_t digest[SHA384_DIGEST_SIZE]; mpz_t x, y; nettle_ecc_point_init(&pubkey, &nettle_secp_384r1); nettle_mpz_init_set_str_256_u(x, SHA384_DIGEST_SIZE, key); nettle_mpz_init_set_str_256_u(y, SHA384_DIGEST_SIZE, key+SHA384_DIGEST_SIZE); nettle_mpz_set_str_256_u(signature.r, SHA384_DIGEST_SIZE, sigblock); nettle_mpz_set_str_256_u(signature.s, SHA384_DIGEST_SIZE, sigblock+SHA384_DIGEST_SIZE); res = _digest_nettle(SHA384_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf), (unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest); res &= nettle_ecc_point_set(&pubkey, x, y); res &= nettle_ecdsa_verify (&pubkey, SHA384_DIGEST_SIZE, digest, &signature); mpz_clear(x); mpz_clear(y); nettle_ecc_point_clear(&pubkey); break; } default: return "unknown ECDSA algorithm"; } /* Clear and return */ nettle_dsa_signature_clear(&signature); if (!res) return "ECDSA signature verification failed"; else return NULL; } #endif #ifdef USE_ED25519 static char * _verify_nettle_ed25519(sldns_buffer* buf, unsigned char* sigblock, unsigned int sigblock_len, unsigned char* key, unsigned int keylen) { int res = 0; if(sigblock_len != ED25519_SIGNATURE_SIZE) { return "wrong ED25519 signature length"; } if(keylen != ED25519_KEY_SIZE) { return "wrong ED25519 key length"; } res = ed25519_sha512_verify((uint8_t*)key, sldns_buffer_limit(buf), sldns_buffer_begin(buf), (uint8_t*)sigblock); if (!res) return "ED25519 signature verification failed"; else return NULL; } #endif /** * Check a canonical sig+rrset and signature against a dnskey * @param buf: buffer with data to verify, the first rrsig part and the * canonicalized rrset. * @param algo: DNSKEY algorithm. * @param sigblock: signature rdata field from RRSIG * @param sigblock_len: length of sigblock data. * @param key: public key data from DNSKEY RR. * @param keylen: length of keydata. * @param reason: bogus reason in more detail. * @return secure if verification succeeded, bogus on crypto failure, * unchecked on format errors and alloc failures. */ enum sec_status verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock, unsigned int sigblock_len, unsigned char* key, unsigned int keylen, char** reason) { unsigned int digest_size = 0; if (sigblock_len == 0 || keylen == 0) { *reason = "null signature"; return sec_status_bogus; } switch(algo) { #if defined(USE_DSA) && defined(USE_SHA1) case LDNS_DSA: case LDNS_DSA_NSEC3: *reason = _verify_nettle_dsa(buf, sigblock, sigblock_len, key, keylen); if (*reason != NULL) return sec_status_bogus; else return sec_status_secure; #endif /* USE_DSA */ #ifdef USE_SHA1 case LDNS_RSASHA1: case LDNS_RSASHA1_NSEC3: digest_size = (digest_size ? digest_size : SHA1_DIGEST_SIZE); #endif /* double fallthrough annotation to please gcc parser */ /* fallthrough */ #ifdef USE_SHA2 /* fallthrough */ case LDNS_RSASHA256: digest_size = (digest_size ? digest_size : SHA256_DIGEST_SIZE); /* fallthrough */ case LDNS_RSASHA512: digest_size = (digest_size ? digest_size : SHA512_DIGEST_SIZE); #endif *reason = _verify_nettle_rsa(buf, digest_size, (char*)sigblock, sigblock_len, key, keylen); if (*reason != NULL) return sec_status_bogus; else return sec_status_secure; #ifdef USE_ECDSA case LDNS_ECDSAP256SHA256: digest_size = (digest_size ? digest_size : SHA256_DIGEST_SIZE); /* fallthrough */ case LDNS_ECDSAP384SHA384: digest_size = (digest_size ? digest_size : SHA384_DIGEST_SIZE); *reason = _verify_nettle_ecdsa(buf, digest_size, sigblock, sigblock_len, key, keylen); if (*reason != NULL) return sec_status_bogus; else return sec_status_secure; #endif #ifdef USE_ED25519 case LDNS_ED25519: *reason = _verify_nettle_ed25519(buf, sigblock, sigblock_len, key, keylen); if (*reason != NULL) return sec_status_bogus; else return sec_status_secure; #endif case LDNS_RSAMD5: case LDNS_ECC_GOST: default: *reason = "unable to verify signature, unknown algorithm"; return sec_status_bogus; } } #endif /* HAVE_SSL or HAVE_NSS or HAVE_NETTLE */ getdns-1.5.1/src/util/lruhash.c0000644000175000017500000004241113416117763013314 00000000000000/* * util/storage/lruhash.c - hashtable, hash function, LRU keeping. * * Copyright (c) 2007, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. */ /** * \file * * This file contains a hashtable with LRU keeping of entries. * */ #include "config.h" #include "util/storage/lruhash.h" #include "util/fptr_wlist.h" void bin_init(struct lruhash_bin* array, size_t size) { size_t i; #ifdef THREADS_DISABLED (void)array; #endif for(i=0; ilock); table->sizefunc = sizefunc; table->compfunc = compfunc; table->delkeyfunc = delkeyfunc; table->deldatafunc = deldatafunc; table->cb_arg = arg; table->size = start_size; table->size_mask = (int)(start_size-1); table->lru_start = NULL; table->lru_end = NULL; table->num = 0; table->space_used = 0; table->space_max = maxmem; table->array = calloc(table->size, sizeof(struct lruhash_bin)); if(!table->array) { lock_quick_destroy(&table->lock); free(table); return NULL; } bin_init(table->array, table->size); lock_protect(&table->lock, table, sizeof(*table)); lock_protect(&table->lock, table->array, table->size*sizeof(struct lruhash_bin)); return table; } void bin_delete(struct lruhash* table, struct lruhash_bin* bin) { struct lruhash_entry* p, *np; void *d; if(!bin) return; lock_quick_destroy(&bin->lock); p = bin->overflow_list; bin->overflow_list = NULL; while(p) { np = p->overflow_next; d = p->data; (*table->delkeyfunc)(p->key, table->cb_arg); (*table->deldatafunc)(d, table->cb_arg); p = np; } } void bin_split(struct lruhash* table, struct lruhash_bin* newa, int newmask) { size_t i; struct lruhash_entry *p, *np; struct lruhash_bin* newbin; /* move entries to new table. Notice that since hash x is mapped to * bin x & mask, and new mask uses one more bit, so all entries in * one bin will go into the old bin or bin | newbit */ #ifndef THREADS_DISABLED int newbit = newmask - table->size_mask; #endif /* so, really, this task could also be threaded, per bin. */ /* LRU list is not changed */ for(i=0; isize; i++) { lock_quick_lock(&table->array[i].lock); p = table->array[i].overflow_list; /* lock both destination bins */ lock_quick_lock(&newa[i].lock); lock_quick_lock(&newa[newbit|i].lock); while(p) { np = p->overflow_next; /* link into correct new bin */ newbin = &newa[p->hash & newmask]; p->overflow_next = newbin->overflow_list; newbin->overflow_list = p; p=np; } lock_quick_unlock(&newa[i].lock); lock_quick_unlock(&newa[newbit|i].lock); lock_quick_unlock(&table->array[i].lock); } } void lruhash_delete(struct lruhash* table) { size_t i; if(!table) return; /* delete lock on hashtable to force check its OK */ lock_quick_destroy(&table->lock); for(i=0; isize; i++) bin_delete(table, &table->array[i]); free(table->array); free(table); } void bin_overflow_remove(struct lruhash_bin* bin, struct lruhash_entry* entry) { struct lruhash_entry* p = bin->overflow_list; struct lruhash_entry** prevp = &bin->overflow_list; while(p) { if(p == entry) { *prevp = p->overflow_next; return; } prevp = &p->overflow_next; p = p->overflow_next; } } void reclaim_space(struct lruhash* table, struct lruhash_entry** list) { struct lruhash_entry* d; struct lruhash_bin* bin; log_assert(table); /* does not delete MRU entry, so table will not be empty. */ while(table->num > 1 && table->space_used > table->space_max) { /* notice that since we hold the hashtable lock, nobody can change the lru chain. So it cannot be deleted underneath us. We still need the hashbin and entry write lock to make sure we flush all users away from the entry. which is unlikely, since it is LRU, if someone got a rdlock it would be moved to front, but to be sure. */ d = table->lru_end; /* specialised, delete from end of double linked list, and we know num>1, so there is a previous lru entry. */ log_assert(d && d->lru_prev); table->lru_end = d->lru_prev; d->lru_prev->lru_next = NULL; /* schedule entry for deletion */ bin = &table->array[d->hash & table->size_mask]; table->num --; lock_quick_lock(&bin->lock); bin_overflow_remove(bin, d); d->overflow_next = *list; *list = d; lock_rw_wrlock(&d->lock); table->space_used -= table->sizefunc(d->key, d->data); if(table->markdelfunc) (*table->markdelfunc)(d->key); lock_rw_unlock(&d->lock); lock_quick_unlock(&bin->lock); } } struct lruhash_entry* bin_find_entry(struct lruhash* table, struct lruhash_bin* bin, hashvalue_type hash, void* key) { struct lruhash_entry* p = bin->overflow_list; while(p) { if(p->hash == hash && table->compfunc(p->key, key) == 0) return p; p = p->overflow_next; } return NULL; } void table_grow(struct lruhash* table) { struct lruhash_bin* newa; int newmask; size_t i; if(table->size_mask == (int)(((size_t)-1)>>1)) { log_err("hash array malloc: size_t too small"); return; } /* try to allocate new array, if not fail */ newa = calloc(table->size*2, sizeof(struct lruhash_bin)); if(!newa) { log_err("hash grow: malloc failed"); /* continue with smaller array. Though its slower. */ return; } bin_init(newa, table->size*2); newmask = (table->size_mask << 1) | 1; bin_split(table, newa, newmask); /* delete the old bins */ lock_unprotect(&table->lock, table->array); for(i=0; isize; i++) { lock_quick_destroy(&table->array[i].lock); } free(table->array); table->size *= 2; table->size_mask = newmask; table->array = newa; lock_protect(&table->lock, table->array, table->size*sizeof(struct lruhash_bin)); return; } void lru_front(struct lruhash* table, struct lruhash_entry* entry) { entry->lru_prev = NULL; entry->lru_next = table->lru_start; if(!table->lru_start) table->lru_end = entry; else table->lru_start->lru_prev = entry; table->lru_start = entry; } void lru_remove(struct lruhash* table, struct lruhash_entry* entry) { if(entry->lru_prev) entry->lru_prev->lru_next = entry->lru_next; else table->lru_start = entry->lru_next; if(entry->lru_next) entry->lru_next->lru_prev = entry->lru_prev; else table->lru_end = entry->lru_prev; } void lru_touch(struct lruhash* table, struct lruhash_entry* entry) { log_assert(table && entry); if(entry == table->lru_start) return; /* nothing to do */ /* remove from current lru position */ lru_remove(table, entry); /* add at front */ lru_front(table, entry); } void lruhash_insert(struct lruhash* table, hashvalue_type hash, struct lruhash_entry* entry, void* data, void* cb_arg) { struct lruhash_bin* bin; struct lruhash_entry* found, *reclaimlist=NULL; size_t need_size; fptr_ok(fptr_whitelist_hash_sizefunc(table->sizefunc)); fptr_ok(fptr_whitelist_hash_delkeyfunc(table->delkeyfunc)); fptr_ok(fptr_whitelist_hash_deldatafunc(table->deldatafunc)); fptr_ok(fptr_whitelist_hash_compfunc(table->compfunc)); fptr_ok(fptr_whitelist_hash_markdelfunc(table->markdelfunc)); need_size = table->sizefunc(entry->key, data); if(cb_arg == NULL) cb_arg = table->cb_arg; /* find bin */ lock_quick_lock(&table->lock); bin = &table->array[hash & table->size_mask]; lock_quick_lock(&bin->lock); /* see if entry exists already */ if(!(found=bin_find_entry(table, bin, hash, entry->key))) { /* if not: add to bin */ entry->overflow_next = bin->overflow_list; bin->overflow_list = entry; lru_front(table, entry); table->num++; table->space_used += need_size; } else { /* if so: update data - needs a writelock */ table->space_used += need_size - (*table->sizefunc)(found->key, found->data); (*table->delkeyfunc)(entry->key, cb_arg); lru_touch(table, found); lock_rw_wrlock(&found->lock); (*table->deldatafunc)(found->data, cb_arg); found->data = data; lock_rw_unlock(&found->lock); } lock_quick_unlock(&bin->lock); if(table->space_used > table->space_max) reclaim_space(table, &reclaimlist); if(table->num >= table->size) table_grow(table); lock_quick_unlock(&table->lock); /* finish reclaim if any (outside of critical region) */ while(reclaimlist) { struct lruhash_entry* n = reclaimlist->overflow_next; void* d = reclaimlist->data; (*table->delkeyfunc)(reclaimlist->key, cb_arg); (*table->deldatafunc)(d, cb_arg); reclaimlist = n; } } struct lruhash_entry* lruhash_lookup(struct lruhash* table, hashvalue_type hash, void* key, int wr) { struct lruhash_entry* entry; struct lruhash_bin* bin; fptr_ok(fptr_whitelist_hash_compfunc(table->compfunc)); lock_quick_lock(&table->lock); bin = &table->array[hash & table->size_mask]; lock_quick_lock(&bin->lock); if((entry=bin_find_entry(table, bin, hash, key))) lru_touch(table, entry); lock_quick_unlock(&table->lock); if(entry) { if(wr) { lock_rw_wrlock(&entry->lock); } else { lock_rw_rdlock(&entry->lock); } } lock_quick_unlock(&bin->lock); return entry; } void lruhash_remove(struct lruhash* table, hashvalue_type hash, void* key) { struct lruhash_entry* entry; struct lruhash_bin* bin; void *d; fptr_ok(fptr_whitelist_hash_sizefunc(table->sizefunc)); fptr_ok(fptr_whitelist_hash_delkeyfunc(table->delkeyfunc)); fptr_ok(fptr_whitelist_hash_deldatafunc(table->deldatafunc)); fptr_ok(fptr_whitelist_hash_compfunc(table->compfunc)); fptr_ok(fptr_whitelist_hash_markdelfunc(table->markdelfunc)); lock_quick_lock(&table->lock); bin = &table->array[hash & table->size_mask]; lock_quick_lock(&bin->lock); if((entry=bin_find_entry(table, bin, hash, key))) { bin_overflow_remove(bin, entry); lru_remove(table, entry); } else { lock_quick_unlock(&table->lock); lock_quick_unlock(&bin->lock); return; } table->num--; table->space_used -= (*table->sizefunc)(entry->key, entry->data); lock_quick_unlock(&table->lock); lock_rw_wrlock(&entry->lock); if(table->markdelfunc) (*table->markdelfunc)(entry->key); lock_rw_unlock(&entry->lock); lock_quick_unlock(&bin->lock); /* finish removal */ d = entry->data; (*table->delkeyfunc)(entry->key, table->cb_arg); (*table->deldatafunc)(d, table->cb_arg); } /** clear bin, respecting locks, does not do space, LRU */ static void bin_clear(struct lruhash* table, struct lruhash_bin* bin) { struct lruhash_entry* p, *np; void *d; lock_quick_lock(&bin->lock); p = bin->overflow_list; while(p) { lock_rw_wrlock(&p->lock); np = p->overflow_next; d = p->data; if(table->markdelfunc) (*table->markdelfunc)(p->key); lock_rw_unlock(&p->lock); (*table->delkeyfunc)(p->key, table->cb_arg); (*table->deldatafunc)(d, table->cb_arg); p = np; } bin->overflow_list = NULL; lock_quick_unlock(&bin->lock); } void lruhash_clear(struct lruhash* table) { size_t i; if(!table) return; fptr_ok(fptr_whitelist_hash_delkeyfunc(table->delkeyfunc)); fptr_ok(fptr_whitelist_hash_deldatafunc(table->deldatafunc)); fptr_ok(fptr_whitelist_hash_markdelfunc(table->markdelfunc)); lock_quick_lock(&table->lock); for(i=0; isize; i++) { bin_clear(table, &table->array[i]); } table->lru_start = NULL; table->lru_end = NULL; table->num = 0; table->space_used = 0; lock_quick_unlock(&table->lock); } void lruhash_status(struct lruhash* table, const char* id, int extended) { lock_quick_lock(&table->lock); log_info("%s: %u entries, memory %u / %u", id, (unsigned)table->num, (unsigned)table->space_used, (unsigned)table->space_max); log_info(" itemsize %u, array %u, mask %d", (unsigned)(table->num? table->space_used/table->num : 0), (unsigned)table->size, table->size_mask); if(extended) { size_t i; int min=(int)table->size*2, max=-2; for(i=0; isize; i++) { int here = 0; struct lruhash_entry *en; lock_quick_lock(&table->array[i].lock); en = table->array[i].overflow_list; while(en) { here ++; en = en->overflow_next; } lock_quick_unlock(&table->array[i].lock); if(extended >= 2) log_info("bin[%d] %d", (int)i, here); if(here > max) max = here; if(here < min) min = here; } log_info(" bin min %d, avg %.2lf, max %d", min, (double)table->num/(double)table->size, max); } lock_quick_unlock(&table->lock); } size_t lruhash_get_mem(struct lruhash* table) { size_t s; lock_quick_lock(&table->lock); s = sizeof(struct lruhash) + table->space_used; #ifdef USE_THREAD_DEBUG if(table->size != 0) { size_t i; for(i=0; isize; i++) s += sizeof(struct lruhash_bin) + lock_get_mem(&table->array[i].lock); } #else /* no THREAD_DEBUG */ if(table->size != 0) s += (table->size)*(sizeof(struct lruhash_bin) + lock_get_mem(&table->array[0].lock)); #endif lock_quick_unlock(&table->lock); s += lock_get_mem(&table->lock); return s; } void lruhash_setmarkdel(struct lruhash* table, lruhash_markdelfunc_type md) { lock_quick_lock(&table->lock); table->markdelfunc = md; lock_quick_unlock(&table->lock); } void lruhash_traverse(struct lruhash* h, int wr, void (*func)(struct lruhash_entry*, void*), void* arg) { size_t i; struct lruhash_entry* e; lock_quick_lock(&h->lock); for(i=0; isize; i++) { lock_quick_lock(&h->array[i].lock); for(e = h->array[i].overflow_list; e; e = e->overflow_next) { if(wr) { lock_rw_wrlock(&e->lock); } else { lock_rw_rdlock(&e->lock); } (*func)(e, arg); lock_rw_unlock(&e->lock); } lock_quick_unlock(&h->array[i].lock); } lock_quick_unlock(&h->lock); } /* * Demote: the opposite of touch, move an entry to the bottom * of the LRU pile. */ void lru_demote(struct lruhash* table, struct lruhash_entry* entry) { log_assert(table && entry); if (entry == table->lru_end) return; /* nothing to do */ /* remove from current lru position */ lru_remove(table, entry); /* add at end */ entry->lru_next = NULL; entry->lru_prev = table->lru_end; if (table->lru_end == NULL) { table->lru_start = entry; } else { table->lru_end->lru_next = entry; } table->lru_end = entry; } struct lruhash_entry* lruhash_insert_or_retrieve(struct lruhash* table, hashvalue_type hash, struct lruhash_entry* entry, void* data, void* cb_arg) { struct lruhash_bin* bin; struct lruhash_entry* found, *reclaimlist = NULL; size_t need_size; fptr_ok(fptr_whitelist_hash_sizefunc(table->sizefunc)); fptr_ok(fptr_whitelist_hash_delkeyfunc(table->delkeyfunc)); fptr_ok(fptr_whitelist_hash_deldatafunc(table->deldatafunc)); fptr_ok(fptr_whitelist_hash_compfunc(table->compfunc)); fptr_ok(fptr_whitelist_hash_markdelfunc(table->markdelfunc)); need_size = table->sizefunc(entry->key, data); if (cb_arg == NULL) cb_arg = table->cb_arg; /* find bin */ lock_quick_lock(&table->lock); bin = &table->array[hash & table->size_mask]; lock_quick_lock(&bin->lock); /* see if entry exists already */ if ((found = bin_find_entry(table, bin, hash, entry->key)) != NULL) { /* if so: keep the existing data - acquire a writelock */ lock_rw_wrlock(&found->lock); } else { /* if not: add to bin */ entry->overflow_next = bin->overflow_list; bin->overflow_list = entry; lru_front(table, entry); table->num++; table->space_used += need_size; /* return the entry that was presented, and lock it */ found = entry; lock_rw_wrlock(&found->lock); } lock_quick_unlock(&bin->lock); if (table->space_used > table->space_max) reclaim_space(table, &reclaimlist); if (table->num >= table->size) table_grow(table); lock_quick_unlock(&table->lock); /* finish reclaim if any (outside of critical region) */ while (reclaimlist) { struct lruhash_entry* n = reclaimlist->overflow_next; void* d = reclaimlist->data; (*table->delkeyfunc)(reclaimlist->key, cb_arg); (*table->deldatafunc)(d, cb_arg); reclaimlist = n; } /* return the entry that was selected */ return found; } getdns-1.5.1/src/util/lookup3.h0000644000175000017500000000352313416117763013250 00000000000000/** * * \file lookup3.h * /brief Alternative symbol names for unbound's lookup3.h * */ /* * Copyright (c) 2017, NLnet Labs, the getdns team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef LOOKUP3_H_SYMBOLS #define LOOKUP3_H_SYMBOLS #define hashword _getdns_hashword #define hashlittle _getdns_hashlittle #define hash_set_raninit _getdns_hash_set_raninit #include "util/orig-headers/lookup3.h" #endif getdns-1.5.1/src/util/locks.c0000644000175000017500000001760313416117763012766 00000000000000/** * util/locks.c - unbound locking primitives * * Copyright (c) 2007, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. */ /** * \file * Implementation of locking and threading support. * A place for locking debug code since most locking functions are macros. */ #include "config.h" #include "util/locks.h" #include #ifdef HAVE_SYS_WAIT_H #include #endif /** block all signals, masks them away. */ void ub_thread_blocksigs(void) { #if defined(HAVE_PTHREAD) || defined(HAVE_SOLARIS_THREADS) || defined(HAVE_SIGPROCMASK) # if defined(HAVE_PTHREAD) || defined(HAVE_SOLARIS_THREADS) int err; # endif sigset_t sigset; sigfillset(&sigset); #ifdef HAVE_PTHREAD if((err=pthread_sigmask(SIG_SETMASK, &sigset, NULL))) fatal_exit("pthread_sigmask: %s", strerror(err)); #else # ifdef HAVE_SOLARIS_THREADS if((err=thr_sigsetmask(SIG_SETMASK, &sigset, NULL))) fatal_exit("thr_sigsetmask: %s", strerror(err)); # else /* have nothing, do single process signal mask */ if(sigprocmask(SIG_SETMASK, &sigset, NULL)) fatal_exit("sigprocmask: %s", strerror(errno)); # endif /* HAVE_SOLARIS_THREADS */ #endif /* HAVE_PTHREAD */ #endif /* have signal stuff */ } /** unblock one signal, so we can catch it */ void ub_thread_sig_unblock(int sig) { #if defined(HAVE_PTHREAD) || defined(HAVE_SOLARIS_THREADS) || defined(HAVE_SIGPROCMASK) # if defined(HAVE_PTHREAD) || defined(HAVE_SOLARIS_THREADS) int err; # endif sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, sig); #ifdef HAVE_PTHREAD if((err=pthread_sigmask(SIG_UNBLOCK, &sigset, NULL))) fatal_exit("pthread_sigmask: %s", strerror(err)); #else # ifdef HAVE_SOLARIS_THREADS if((err=thr_sigsetmask(SIG_UNBLOCK, &sigset, NULL))) fatal_exit("thr_sigsetmask: %s", strerror(err)); # else /* have nothing, do single thread case */ if(sigprocmask(SIG_UNBLOCK, &sigset, NULL)) fatal_exit("sigprocmask: %s", strerror(errno)); # endif /* HAVE_SOLARIS_THREADS */ #endif /* HAVE_PTHREAD */ #else (void)sig; #endif /* have signal stuff */ } #if !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS) && !defined(HAVE_WINDOWS_THREADS) /** * No threading available: fork a new process. * This means no shared data structure, and no locking. * Only the main thread ever returns. Exits on errors. * @param thr: the location where to store the thread-id. * @param func: function body of the thread. Return value of func is lost. * @param arg: user argument to func. */ void ub_thr_fork_create(ub_thread_type* thr, void* (*func)(void*), void* arg) { pid_t pid = fork(); switch(pid) { default: /* main */ *thr = (ub_thread_type)pid; return; case 0: /* child */ *thr = (ub_thread_type)getpid(); (void)(*func)(arg); exit(0); case -1: /* error */ fatal_exit("could not fork: %s", strerror(errno)); } } /** * There is no threading. Wait for a process to terminate. * Note that ub_thread_type is defined as pid_t. * @param thread: the process id to wait for. */ void ub_thr_fork_wait(ub_thread_type thread) { int status = 0; if(waitpid((pid_t)thread, &status, 0) == -1) log_err("waitpid(%d): %s", (int)thread, strerror(errno)); if(status != 0) log_warn("process %d abnormal exit with status %d", (int)thread, status); } #endif /* !defined(HAVE_PTHREAD) && !defined(HAVE_SOLARIS_THREADS) && !defined(HAVE_WINDOWS_THREADS) */ #ifdef HAVE_SOLARIS_THREADS void* ub_thread_key_get(ub_thread_key_type key) { void* ret=NULL; LOCKRET(thr_getspecific(key, &ret)); return ret; } #endif #ifdef HAVE_WINDOWS_THREADS /** log a windows GetLastError message */ static void log_win_err(const char* str, DWORD err) { LPTSTR buf; if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, err, 0, (LPTSTR)&buf, 0, NULL) == 0) { /* could not format error message */ log_err("%s, GetLastError=%d", str, (int)err); return; } log_err("%s, (err=%d): %s", str, (int)err, buf); LocalFree(buf); } void lock_basic_init(lock_basic_type* lock) { /* implement own lock, because windows HANDLE as Mutex usage * uses too many handles and would bog down the whole system. */ (void)InterlockedExchange(lock, 0); } void lock_basic_destroy(lock_basic_type* lock) { (void)InterlockedExchange(lock, 0); } void lock_basic_lock(lock_basic_type* lock) { LONG wait = 1; /* wait 1 msec at first */ while(InterlockedExchange(lock, 1)) { /* if the old value was 1 then if was already locked */ Sleep(wait); /* wait with sleep */ wait *= 2; /* exponential backoff for waiting */ } /* the old value was 0, but we inserted 1, we locked it! */ } void lock_basic_unlock(lock_basic_type* lock) { /* unlock it by inserting the value of 0. xchg for cache coherency. */ (void)InterlockedExchange(lock, 0); } void ub_thread_key_create(ub_thread_key_type* key, void* f) { *key = TlsAlloc(); if(*key == TLS_OUT_OF_INDEXES) { *key = 0; log_win_err("TlsAlloc Failed(OUT_OF_INDEXES)", GetLastError()); } else ub_thread_key_set(*key, f); } void ub_thread_key_set(ub_thread_key_type key, void* v) { if(!TlsSetValue(key, v)) { log_win_err("TlsSetValue failed", GetLastError()); } } void* ub_thread_key_get(ub_thread_key_type key) { void* ret = (void*)TlsGetValue(key); if(ret == NULL && GetLastError() != ERROR_SUCCESS) { log_win_err("TlsGetValue failed", GetLastError()); } return ret; } void ub_thread_create(ub_thread_type* thr, void* (*func)(void*), void* arg) { #ifndef HAVE__BEGINTHREADEX *thr = CreateThread(NULL, /* default security (no inherit handle) */ 0, /* default stack size */ (LPTHREAD_START_ROUTINE)func, arg, 0, /* default flags, run immediately */ NULL); /* do not store thread identifier anywhere */ #else /* the beginthreadex routine setups for the C lib; aligns stack */ *thr=(ub_thread_type)_beginthreadex(NULL, 0, (void*)func, arg, 0, NULL); #endif if(*thr == NULL) { log_win_err("CreateThread failed", GetLastError()); fatal_exit("thread create failed"); } } ub_thread_type ub_thread_self(void) { return GetCurrentThread(); } void ub_thread_join(ub_thread_type thr) { DWORD ret = WaitForSingleObject(thr, INFINITE); if(ret == WAIT_FAILED) { log_win_err("WaitForSingleObject(Thread):WAIT_FAILED", GetLastError()); } else if(ret == WAIT_TIMEOUT) { log_win_err("WaitForSingleObject(Thread):WAIT_TIMEOUT", GetLastError()); } /* and close the handle to the thread */ if(!CloseHandle(thr)) { log_win_err("CloseHandle(Thread) failed", GetLastError()); } } #endif /* HAVE_WINDOWS_THREADS */ getdns-1.5.1/src/util/rbtree.c0000644000175000017500000004012613416117763013132 00000000000000/* * rbtree.c -- generic red black tree * * Copyright (c) 2001-2007, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. * */ /** * \file * Implementation of a redblack tree. */ #include "config.h" #include "log.h" #include "fptr_wlist.h" #include "util/rbtree.h" /** Node colour black */ #define BLACK 0 /** Node colour red */ #define RED 1 /** the NULL node, global alloc */ rbnode_type rbtree_null_node = { RBTREE_NULL, /* Parent. */ RBTREE_NULL, /* Left. */ RBTREE_NULL, /* Right. */ NULL, /* Key. */ BLACK /* Color. */ }; /** rotate subtree left (to preserve redblack property) */ static void rbtree_rotate_left(rbtree_type *rbtree, rbnode_type *node); /** rotate subtree right (to preserve redblack property) */ static void rbtree_rotate_right(rbtree_type *rbtree, rbnode_type *node); /** Fixup node colours when insert happened */ static void rbtree_insert_fixup(rbtree_type *rbtree, rbnode_type *node); /** Fixup node colours when delete happened */ static void rbtree_delete_fixup(rbtree_type* rbtree, rbnode_type* child, rbnode_type* child_parent); /* * Creates a new red black tree, initializes and returns a pointer to it. * * Return NULL on failure. * */ rbtree_type * rbtree_create (int (*cmpf)(const void *, const void *)) { rbtree_type *rbtree; /* Allocate memory for it */ rbtree = (rbtree_type *) malloc(sizeof(rbtree_type)); if (!rbtree) { return NULL; } /* Initialize it */ rbtree_init(rbtree, cmpf); return rbtree; } void rbtree_init(rbtree_type *rbtree, int (*cmpf)(const void *, const void *)) { /* Initialize it */ rbtree->root = RBTREE_NULL; rbtree->count = 0; rbtree->cmp = cmpf; } /* * Rotates the node to the left. * */ static void rbtree_rotate_left(rbtree_type *rbtree, rbnode_type *node) { rbnode_type *right = node->right; node->right = right->left; if (right->left != RBTREE_NULL) right->left->parent = node; right->parent = node->parent; if (node->parent != RBTREE_NULL) { if (node == node->parent->left) { node->parent->left = right; } else { node->parent->right = right; } } else { rbtree->root = right; } right->left = node; node->parent = right; } /* * Rotates the node to the right. * */ static void rbtree_rotate_right(rbtree_type *rbtree, rbnode_type *node) { rbnode_type *left = node->left; node->left = left->right; if (left->right != RBTREE_NULL) left->right->parent = node; left->parent = node->parent; if (node->parent != RBTREE_NULL) { if (node == node->parent->right) { node->parent->right = left; } else { node->parent->left = left; } } else { rbtree->root = left; } left->right = node; node->parent = left; } static void rbtree_insert_fixup(rbtree_type *rbtree, rbnode_type *node) { rbnode_type *uncle; /* While not at the root and need fixing... */ while (node != rbtree->root && node->parent->color == RED) { /* If our parent is left child of our grandparent... */ if (node->parent == node->parent->parent->left) { uncle = node->parent->parent->right; /* If our uncle is red... */ if (uncle->color == RED) { /* Paint the parent and the uncle black... */ node->parent->color = BLACK; uncle->color = BLACK; /* And the grandparent red... */ node->parent->parent->color = RED; /* And continue fixing the grandparent */ node = node->parent->parent; } else { /* Our uncle is black... */ /* Are we the right child? */ if (node == node->parent->right) { node = node->parent; rbtree_rotate_left(rbtree, node); } /* Now we're the left child, repaint and rotate... */ node->parent->color = BLACK; node->parent->parent->color = RED; rbtree_rotate_right(rbtree, node->parent->parent); } } else { uncle = node->parent->parent->left; /* If our uncle is red... */ if (uncle->color == RED) { /* Paint the parent and the uncle black... */ node->parent->color = BLACK; uncle->color = BLACK; /* And the grandparent red... */ node->parent->parent->color = RED; /* And continue fixing the grandparent */ node = node->parent->parent; } else { /* Our uncle is black... */ /* Are we the right child? */ if (node == node->parent->left) { node = node->parent; rbtree_rotate_right(rbtree, node); } /* Now we're the right child, repaint and rotate... */ node->parent->color = BLACK; node->parent->parent->color = RED; rbtree_rotate_left(rbtree, node->parent->parent); } } } rbtree->root->color = BLACK; } /* * Inserts a node into a red black tree. * * Returns NULL on failure or the pointer to the newly added node * otherwise. */ rbnode_type * rbtree_insert (rbtree_type *rbtree, rbnode_type *data) { /* XXX Not necessary, but keeps compiler quiet... */ int r = 0; /* We start at the root of the tree */ rbnode_type *node = rbtree->root; rbnode_type *parent = RBTREE_NULL; fptr_ok(fptr_whitelist_rbtree_cmp(rbtree->cmp)); /* Lets find the new parent... */ while (node != RBTREE_NULL) { /* Compare two keys, do we have a duplicate? */ if ((r = rbtree->cmp(data->key, node->key)) == 0) { return NULL; } parent = node; if (r < 0) { node = node->left; } else { node = node->right; } } /* Initialize the new node */ data->parent = parent; data->left = data->right = RBTREE_NULL; data->color = RED; rbtree->count++; /* Insert it into the tree... */ if (parent != RBTREE_NULL) { if (r < 0) { parent->left = data; } else { parent->right = data; } } else { rbtree->root = data; } /* Fix up the red-black properties... */ rbtree_insert_fixup(rbtree, data); return data; } /* * Searches the red black tree, returns the data if key is found or NULL otherwise. * */ rbnode_type * rbtree_search (rbtree_type *rbtree, const void *key) { rbnode_type *node; if (rbtree_find_less_equal(rbtree, key, &node)) { return node; } else { return NULL; } } /** helpers for delete: swap node colours */ static void swap_int8(uint8_t* x, uint8_t* y) { uint8_t t = *x; *x = *y; *y = t; } /** helpers for delete: swap node pointers */ static void swap_np(rbnode_type** x, rbnode_type** y) { rbnode_type* t = *x; *x = *y; *y = t; } /** Update parent pointers of child trees of 'parent' */ static void change_parent_ptr(rbtree_type* rbtree, rbnode_type* parent, rbnode_type* old, rbnode_type* new) { if(parent == RBTREE_NULL) { log_assert(rbtree->root == old); if(rbtree->root == old) rbtree->root = new; return; } log_assert(parent->left == old || parent->right == old || parent->left == new || parent->right == new); if(parent->left == old) parent->left = new; if(parent->right == old) parent->right = new; } /** Update parent pointer of a node 'child' */ static void change_child_ptr(rbnode_type* child, rbnode_type* old, rbnode_type* new) { if(child == RBTREE_NULL) return; log_assert(child->parent == old || child->parent == new); if(child->parent == old) child->parent = new; } rbnode_type* rbtree_delete(rbtree_type *rbtree, const void *key) { rbnode_type *to_delete; rbnode_type *child; if((to_delete = rbtree_search(rbtree, key)) == 0) return 0; rbtree->count--; /* make sure we have at most one non-leaf child */ if(to_delete->left != RBTREE_NULL && to_delete->right != RBTREE_NULL) { /* swap with smallest from right subtree (or largest from left) */ rbnode_type *smright = to_delete->right; while(smright->left != RBTREE_NULL) smright = smright->left; /* swap the smright and to_delete elements in the tree, * but the rbnode_type is first part of user data struct * so cannot just swap the keys and data pointers. Instead * readjust the pointers left,right,parent */ /* swap colors - colors are tied to the position in the tree */ swap_int8(&to_delete->color, &smright->color); /* swap child pointers in parents of smright/to_delete */ change_parent_ptr(rbtree, to_delete->parent, to_delete, smright); if(to_delete->right != smright) change_parent_ptr(rbtree, smright->parent, smright, to_delete); /* swap parent pointers in children of smright/to_delete */ change_child_ptr(smright->left, smright, to_delete); change_child_ptr(smright->left, smright, to_delete); change_child_ptr(smright->right, smright, to_delete); change_child_ptr(smright->right, smright, to_delete); change_child_ptr(to_delete->left, to_delete, smright); if(to_delete->right != smright) change_child_ptr(to_delete->right, to_delete, smright); if(to_delete->right == smright) { /* set up so after swap they work */ to_delete->right = to_delete; smright->parent = smright; } /* swap pointers in to_delete/smright nodes */ swap_np(&to_delete->parent, &smright->parent); swap_np(&to_delete->left, &smright->left); swap_np(&to_delete->right, &smright->right); /* now delete to_delete (which is at the location where the smright previously was) */ } log_assert(to_delete->left == RBTREE_NULL || to_delete->right == RBTREE_NULL); if(to_delete->left != RBTREE_NULL) child = to_delete->left; else child = to_delete->right; /* unlink to_delete from the tree, replace to_delete with child */ change_parent_ptr(rbtree, to_delete->parent, to_delete, child); change_child_ptr(child, to_delete, to_delete->parent); if(to_delete->color == RED) { /* if node is red then the child (black) can be swapped in */ } else if(child->color == RED) { /* change child to BLACK, removing a RED node is no problem */ if(child!=RBTREE_NULL) child->color = BLACK; } else rbtree_delete_fixup(rbtree, child, to_delete->parent); /* unlink completely */ to_delete->parent = RBTREE_NULL; to_delete->left = RBTREE_NULL; to_delete->right = RBTREE_NULL; to_delete->color = BLACK; return to_delete; } static void rbtree_delete_fixup(rbtree_type* rbtree, rbnode_type* child, rbnode_type* child_parent) { rbnode_type* sibling; int go_up = 1; /* determine sibling to the node that is one-black short */ if(child_parent->right == child) sibling = child_parent->left; else sibling = child_parent->right; while(go_up) { if(child_parent == RBTREE_NULL) { /* removed parent==black from root, every path, so ok */ return; } if(sibling->color == RED) { /* rotate to get a black sibling */ child_parent->color = RED; sibling->color = BLACK; if(child_parent->right == child) rbtree_rotate_right(rbtree, child_parent); else rbtree_rotate_left(rbtree, child_parent); /* new sibling after rotation */ if(child_parent->right == child) sibling = child_parent->left; else sibling = child_parent->right; } if(child_parent->color == BLACK && sibling->color == BLACK && sibling->left->color == BLACK && sibling->right->color == BLACK) { /* fixup local with recolor of sibling */ if(sibling != RBTREE_NULL) sibling->color = RED; child = child_parent; child_parent = child_parent->parent; /* prepare to go up, new sibling */ if(child_parent->right == child) sibling = child_parent->left; else sibling = child_parent->right; } else go_up = 0; } if(child_parent->color == RED && sibling->color == BLACK && sibling->left->color == BLACK && sibling->right->color == BLACK) { /* move red to sibling to rebalance */ if(sibling != RBTREE_NULL) sibling->color = RED; child_parent->color = BLACK; return; } log_assert(sibling != RBTREE_NULL); /* get a new sibling, by rotating at sibling. See which child of sibling is red */ if(child_parent->right == child && sibling->color == BLACK && sibling->right->color == RED && sibling->left->color == BLACK) { sibling->color = RED; sibling->right->color = BLACK; rbtree_rotate_left(rbtree, sibling); /* new sibling after rotation */ if(child_parent->right == child) sibling = child_parent->left; else sibling = child_parent->right; } else if(child_parent->left == child && sibling->color == BLACK && sibling->left->color == RED && sibling->right->color == BLACK) { sibling->color = RED; sibling->left->color = BLACK; rbtree_rotate_right(rbtree, sibling); /* new sibling after rotation */ if(child_parent->right == child) sibling = child_parent->left; else sibling = child_parent->right; } /* now we have a black sibling with a red child. rotate and exchange colors. */ sibling->color = child_parent->color; child_parent->color = BLACK; if(child_parent->right == child) { log_assert(sibling->left->color == RED); sibling->left->color = BLACK; rbtree_rotate_right(rbtree, child_parent); } else { log_assert(sibling->right->color == RED); sibling->right->color = BLACK; rbtree_rotate_left(rbtree, child_parent); } } int rbtree_find_less_equal(rbtree_type *rbtree, const void *key, rbnode_type **result) { int r; rbnode_type *node; log_assert(result); /* We start at root... */ node = rbtree->root; *result = NULL; fptr_ok(fptr_whitelist_rbtree_cmp(rbtree->cmp)); /* While there are children... */ while (node != RBTREE_NULL) { r = rbtree->cmp(key, node->key); if (r == 0) { /* Exact match */ *result = node; return 1; } if (r < 0) { node = node->left; } else { /* Temporary match */ *result = node; node = node->right; } } return 0; } /* * Finds the first element in the red black tree * */ rbnode_type * rbtree_first (const rbtree_type *rbtree) { rbnode_type *node; for (node = rbtree->root; node->left != RBTREE_NULL; node = node->left); return node; } rbnode_type * rbtree_last (rbtree_type *rbtree) { rbnode_type *node; for (node = rbtree->root; node->right != RBTREE_NULL; node = node->right); return node; } /* * Returns the next node... * */ rbnode_type * rbtree_next (rbnode_type *node) { rbnode_type *parent; if (node->right != RBTREE_NULL) { /* One right, then keep on going left... */ for (node = node->right; node->left != RBTREE_NULL; node = node->left); } else { parent = node->parent; while (parent != RBTREE_NULL && node == parent->right) { node = parent; parent = parent->parent; } node = parent; } return node; } rbnode_type * rbtree_previous(rbnode_type *node) { rbnode_type *parent; if (node->left != RBTREE_NULL) { /* One left, then keep on going right... */ for (node = node->left; node->right != RBTREE_NULL; node = node->right); } else { parent = node->parent; while (parent != RBTREE_NULL && node == parent->left) { node = parent; parent = parent->parent; } node = parent; } return node; } /** recursive descent traverse */ static void traverse_post(void (*func)(rbnode_type*, void*), void* arg, rbnode_type* node) { if(!node || node == RBTREE_NULL) return; /* recurse */ traverse_post(func, arg, node->left); traverse_post(func, arg, node->right); /* call user func */ (*func)(node, arg); } void traverse_postorder(rbtree_type* tree, void (*func)(rbnode_type*, void*), void* arg) { traverse_post(func, arg, tree->root); } getdns-1.5.1/src/util/lruhash.h0000644000175000017500000000630013416117763013316 00000000000000/** * * \file lruhash.h * /brief Alternative symbol names for unbound's lruhash.h * */ /* * Copyright (c) 2017, NLnet Labs, the getdns team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef LRUHASH_H_SYMBOLS #define LRUHASH_H_SYMBOLS #define lruhash _getdns_lruhash #define lruhash_bin _getdns_lruhash_bin #define lruhash_entry _getdns_lruhash_entry #define hashvalue_type _getdns_hashvalue_type #define lruhash_sizefunc_type _getdns_lruhash_sizefunc_type #define lruhash_compfunc_type _getdns_lruhash_compfunc_type #define lruhash_delkeyfunc_type _getdns_lruhash_delkeyfunc_type #define lruhash_deldatafunc_type _getdns_lruhash_deldatafunc_type #define lruhash_markdelfunc_type _getdns_lruhash_markdelfunc_type #define lruhash_create _getdns_lruhash_create #define lruhash_delete _getdns_lruhash_delete #define lruhash_clear _getdns_lruhash_clear #define lruhash_insert _getdns_lruhash_insert #define lruhash_lookup _getdns_lruhash_lookup #define lru_touch _getdns_lru_touch #define lruhash_setmarkdel _getdns_lruhash_setmarkdel #define lru_demote _getdns_lru_demote #define lruhash_insert_or_retrieve _getdns_lruhash_insert_or_retrieve #define lruhash_remove _getdns_lruhash_remove #define bin_init _getdns_bin_init #define bin_delete _getdns_bin_delete #define bin_find_entry _getdns_bin_find_entry #define bin_overflow_remove _getdns_bin_overflow_remove #define bin_split _getdns_bin_split #define reclaim_space _getdns_reclaim_space #define table_grow _getdns_table_grow #define lru_front _getdns_lru_front #define lru_remove _getdns_lru_remove #define lruhash_status _getdns_lruhash_status #define lruhash_get_mem _getdns_lruhash_get_mem #define lruhash_traverse _getdns_lruhash_traverse #include "util/orig-headers/lruhash.h" #endif getdns-1.5.1/src/util/auxiliary/0000755000175000017500000000000013416117763013567 500000000000000getdns-1.5.1/src/util/auxiliary/fptr_wlist.h0000644000175000017500000000003513416117763016053 00000000000000#include "util/fptr_wlist.h" getdns-1.5.1/src/util/auxiliary/sldns/0000755000175000017500000000000013416117763014712 500000000000000getdns-1.5.1/src/util/auxiliary/sldns/keyraw.h0000644000175000017500000000003213416117763016300 00000000000000#include "gldns/keyraw.h" getdns-1.5.1/src/util/auxiliary/sldns/sbuffer.h0000644000175000017500000000003313416117763016433 00000000000000#include "gldns/gbuffer.h" getdns-1.5.1/src/util/auxiliary/sldns/rrdef.h0000644000175000017500000000003113416117763016077 00000000000000#include "gldns/rrdef.h" getdns-1.5.1/src/util/auxiliary/log.h0000644000175000017500000000002613416117763014437 00000000000000#include "util/log.h" getdns-1.5.1/src/util/auxiliary/util/0000755000175000017500000000000013416117763014544 500000000000000getdns-1.5.1/src/util/auxiliary/util/fptr_wlist.h0000644000175000017500000000342113416117763017032 00000000000000/** * * /brief dummy prototypes for function pointer whitelisting * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef UTIL_FPTR_WLIST_H #define UTIL_FPTR_WLIST_H #define fptr_ok(x) #define fptr_whitelist_event(x) #define fptr_whitelist_rbtree_cmp(x) #endif /* UTIL_FPTR_WLIST_H */ getdns-1.5.1/src/util/auxiliary/util/log.h0000644000175000017500000000444513416117763015425 00000000000000/** * * /brief dummy prototypes for logging a la unbound * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef UTIL_LOG_H #define UTIL_LOG_H #include "config.h" #include "debug.h" #ifdef DEBUGGING #define verbose(x, ...) DEBUG_NL(__VA_ARGS__) #define log_err(...) DEBUG_NL(__VA_ARGS__) #define log_info(...) DEBUG_NL(__VA_ARGS__) #define fatal_exit(...) do { DEBUG_NL(__VA_ARGS__); exit(EXIT_FAILURE); } while(0) #define log_assert(x) do { if(!(x)) fatal_exit("%s:%d: %s: assertion %s failed", \ __FILE__, __LINE__, __FUNC__, #x); \ } while(0) #else #define verbose(...) ((void)0) #define log_err(...) ((void)0) #define log_info(...) ((void)0) #define fatal_exit(...) ((void)0) #define log_assert(x) ((void)0) #endif #endif /* UTIL_LOG_H */ getdns-1.5.1/src/util/auxiliary/util/storage/0000755000175000017500000000000013416117763016210 500000000000000getdns-1.5.1/src/util/auxiliary/util/storage/lruhash.h0000644000175000017500000000003213416117763017742 00000000000000#include "util/lruhash.h" getdns-1.5.1/src/util/auxiliary/util/storage/lookup3.h0000644000175000017500000000003213416117763017670 00000000000000#include "util/lookup3.h" getdns-1.5.1/src/util/auxiliary/util/data/0000755000175000017500000000000013416117763015455 500000000000000getdns-1.5.1/src/util/auxiliary/util/data/packed_rrset.h0000644000175000017500000000000113416117763020203 00000000000000 getdns-1.5.1/src/util/auxiliary/validator/0000755000175000017500000000000013416117763015554 500000000000000getdns-1.5.1/src/util/auxiliary/validator/val_secalgo.h0000644000175000017500000000003613416117763020123 00000000000000#include "util/val_secalgo.h" getdns-1.5.1/src/util/auxiliary/validator/val_nsec3.h0000644000175000017500000000000113416117763017511 00000000000000 getdns-1.5.1/src/util/lookup3.c0000644000175000017500000010707513416117763013252 00000000000000/* February 2013(Wouter) patch defines for BSD endianness, from Brad Smith. January 2012(Wouter) added randomised initial value, fallout from 28c3. March 2007(Wouter) adapted from lookup3.c original, add config.h include. added #ifdef VALGRIND to remove 298,384,660 'unused variable k8' warnings. added include of lookup3.h to check definitions match declarations. removed include of stdint - config.h takes care of platform independence. added fallthrough comments for new gcc warning suppression. url http://burtleburtle.net/bob/hash/index.html. */ /* ------------------------------------------------------------------------------- lookup3.c, by Bob Jenkins, May 2006, Public Domain. These are functions for producing 32-bit hashes for hash table lookup. hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() are externally useful functions. Routines to test the hash are included if SELF_TEST is defined. You can use this free for any purpose. It's in the public domain. It has no warranty. You probably want to use hashlittle(). hashlittle() and hashbig() hash byte arrays. hashlittle() is is faster than hashbig() on little-endian machines. Intel and AMD are little-endian machines. On second thought, you probably want hashlittle2(), which is identical to hashlittle() except it returns two 32-bit hashes for the price of one. You could implement hashbig2() if you wanted but I haven't bothered here. If you want to find a hash of, say, exactly 7 integers, do a = i1; b = i2; c = i3; mix(a,b,c); a += i4; b += i5; c += i6; mix(a,b,c); a += i7; final(a,b,c); then use c as the hash value. If you have a variable length array of 4-byte integers to hash, use hashword(). If you have a byte array (like a character string), use hashlittle(). If you have several byte arrays, or a mix of things, see the comments above hashlittle(). Why is this so big? I read 12 bytes at a time into 3 4-byte integers, then mix those integers. This is fast (you can do a lot more thorough mixing with 12*3 instructions on 3 integers than you can with 3 instructions on 1 byte), but shoehorning those bytes into integers efficiently is messy. ------------------------------------------------------------------------------- */ /*#define SELF_TEST 1*/ #include "config.h" #include "util/storage/lookup3.h" #include /* defines printf for tests */ #include /* defines time_t for timings in the test */ /*#include defines uint32_t etc (from config.h) */ #include /* attempt to define endianness */ #ifdef HAVE_SYS_TYPES_H # include /* attempt to define endianness (solaris) */ #endif #if defined(linux) || defined(__OpenBSD__) # ifdef HAVE_ENDIAN_H # include /* attempt to define endianness */ # else # include /* on older OpenBSD */ # endif #endif #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) #include /* attempt to define endianness */ #endif /* random initial value */ static uint32_t raninit = (uint32_t)0xdeadbeef; void hash_set_raninit(uint32_t v) { raninit = v; } /* * My best guess at if you are big-endian or little-endian. This may * need adjustment. */ #if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \ __BYTE_ORDER == __LITTLE_ENDIAN) || \ (defined(i386) || defined(__i386__) || defined(__i486__) || \ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL) || defined(__x86)) # define HASH_LITTLE_ENDIAN 1 # define HASH_BIG_ENDIAN 0 #elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \ __BYTE_ORDER == __BIG_ENDIAN) || \ (defined(sparc) || defined(__sparc) || defined(__sparc__) || defined(POWERPC) || defined(mc68000) || defined(sel)) # define HASH_LITTLE_ENDIAN 0 # define HASH_BIG_ENDIAN 1 #elif defined(_MACHINE_ENDIAN_H_) /* test for machine_endian_h protects failure if some are empty strings */ # if defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && _BYTE_ORDER == _BIG_ENDIAN # define HASH_LITTLE_ENDIAN 0 # define HASH_BIG_ENDIAN 1 # endif # if defined(_BYTE_ORDER) && defined(_LITTLE_ENDIAN) && _BYTE_ORDER == _LITTLE_ENDIAN # define HASH_LITTLE_ENDIAN 1 # define HASH_BIG_ENDIAN 0 # endif /* _MACHINE_ENDIAN_H_ */ #else # define HASH_LITTLE_ENDIAN 0 # define HASH_BIG_ENDIAN 0 #endif #define hashsize(n) ((uint32_t)1<<(n)) #define hashmask(n) (hashsize(n)-1) #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) /* ------------------------------------------------------------------------------- mix -- mix 3 32-bit values reversibly. This is reversible, so any information in (a,b,c) before mix() is still in (a,b,c) after mix(). If four pairs of (a,b,c) inputs are run through mix(), or through mix() in reverse, there are at least 32 bits of the output that are sometimes the same for one pair and different for another pair. This was tested for: * pairs that differed by one bit, by two bits, in any combination of top bits of (a,b,c), or in any combination of bottom bits of (a,b,c). * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. * the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that satisfy this are 4 6 8 16 19 4 9 15 3 18 27 15 14 9 3 7 17 3 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing for "differ" defined as + with a one-bit base and a two-bit delta. I used http://burtleburtle.net/bob/hash/avalanche.html to choose the operations, constants, and arrangements of the variables. This does not achieve avalanche. There are input bits of (a,b,c) that fail to affect some output bits of (a,b,c), especially of a. The most thoroughly mixed value is c, but it doesn't really even achieve avalanche in c. This allows some parallelism. Read-after-writes are good at doubling the number of bits affected, so the goal of mixing pulls in the opposite direction as the goal of parallelism. I did what I could. Rotates seem to cost as much as shifts on every machine I could lay my hands on, and rotates are much kinder to the top and bottom bits, so I used rotates. ------------------------------------------------------------------------------- */ #define mix(a,b,c) \ { \ a -= c; a ^= rot(c, 4); c += b; \ b -= a; b ^= rot(a, 6); a += c; \ c -= b; c ^= rot(b, 8); b += a; \ a -= c; a ^= rot(c,16); c += b; \ b -= a; b ^= rot(a,19); a += c; \ c -= b; c ^= rot(b, 4); b += a; \ } /* ------------------------------------------------------------------------------- final -- final mixing of 3 32-bit values (a,b,c) into c Pairs of (a,b,c) values differing in only a few bits will usually produce values of c that look totally different. This was tested for * pairs that differed by one bit, by two bits, in any combination of top bits of (a,b,c), or in any combination of bottom bits of (a,b,c). * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. * the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. These constants passed: 14 11 25 16 4 14 24 12 14 25 16 4 14 24 and these came close: 4 8 15 26 3 22 24 10 8 15 26 3 22 24 11 8 15 26 3 22 24 ------------------------------------------------------------------------------- */ #define final(a,b,c) \ { \ c ^= b; c -= rot(b,14); \ a ^= c; a -= rot(c,11); \ b ^= a; b -= rot(a,25); \ c ^= b; c -= rot(b,16); \ a ^= c; a -= rot(c,4); \ b ^= a; b -= rot(a,14); \ c ^= b; c -= rot(b,24); \ } /* -------------------------------------------------------------------- This works on all machines. To be useful, it requires -- that the key be an array of uint32_t's, and -- that the length be the number of uint32_t's in the key The function hashword() is identical to hashlittle() on little-endian machines, and identical to hashbig() on big-endian machines, except that the length has to be measured in uint32_ts rather than in bytes. hashlittle() is more complicated than hashword() only because hashlittle() has to dance around fitting the key bytes into registers. -------------------------------------------------------------------- */ uint32_t hashword( const uint32_t *k, /* the key, an array of uint32_t values */ size_t length, /* the length of the key, in uint32_ts */ uint32_t initval) /* the previous hash, or an arbitrary value */ { uint32_t a,b,c; /* Set up the internal state */ a = b = c = raninit + (((uint32_t)length)<<2) + initval; /*------------------------------------------------- handle most of the key */ while (length > 3) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 3; k += 3; } /*------------------------------------------- handle the last 3 uint32_t's */ switch(length) /* all the case statements fall through */ { case 3 : c+=k[2]; /* fallthrough */ case 2 : b+=k[1]; /* fallthrough */ case 1 : a+=k[0]; final(a,b,c); case 0: /* case 0: nothing left to add */ break; } /*------------------------------------------------------ report the result */ return c; } #ifdef SELF_TEST /* -------------------------------------------------------------------- hashword2() -- same as hashword(), but take two seeds and return two 32-bit values. pc and pb must both be nonnull, and *pc and *pb must both be initialized with seeds. If you pass in (*pb)==0, the output (*pc) will be the same as the return value from hashword(). -------------------------------------------------------------------- */ void hashword2 ( const uint32_t *k, /* the key, an array of uint32_t values */ size_t length, /* the length of the key, in uint32_ts */ uint32_t *pc, /* IN: seed OUT: primary hash value */ uint32_t *pb) /* IN: more seed OUT: secondary hash value */ { uint32_t a,b,c; /* Set up the internal state */ a = b = c = raninit + ((uint32_t)(length<<2)) + *pc; c += *pb; /*------------------------------------------------- handle most of the key */ while (length > 3) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 3; k += 3; } /*------------------------------------------- handle the last 3 uint32_t's */ switch(length) /* all the case statements fall through */ { case 3 : c+=k[2]; case 2 : b+=k[1]; case 1 : a+=k[0]; final(a,b,c); case 0: /* case 0: nothing left to add */ break; } /*------------------------------------------------------ report the result */ *pc=c; *pb=b; } #endif /* SELF_TEST */ /* ------------------------------------------------------------------------------- hashlittle() -- hash a variable-length key into a 32-bit value k : the key (the unaligned variable-length array of bytes) length : the length of the key, counting by bytes initval : can be any 4-byte value Returns a 32-bit value. Every bit of the key affects every bit of the return value. Two keys differing by one or two bits will have totally different hash values. The best hash table sizes are powers of 2. There is no need to do mod a prime (mod is sooo slow!). If you need less than 32 bits, use a bitmask. For example, if you need only 10 bits, do h = (h & hashmask(10)); In which case, the hash table should have hashsize(10) elements. If you are hashing n strings (uint8_t **)k, do it like this: for (i=0, h=0; i 12) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 12; k += 3; } /*----------------------------- handle the last (probably partial) block */ /* * "k[2]&0xffffff" actually reads beyond the end of the string, but * then masks off the part it's not allowed to read. Because the * string is aligned, the masked-off tail is in the same word as the * rest of the string. Every machine with memory protection I've seen * does it on word boundaries, so is OK with this. But VALGRIND will * still catch it and complain. The masking trick does make the hash * noticeably faster for short strings (like English words). */ #ifndef VALGRIND switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=k[1]&0xffffff; a+=k[0]; break; case 6 : b+=k[1]&0xffff; a+=k[0]; break; case 5 : b+=k[1]&0xff; a+=k[0]; break; case 4 : a+=k[0]; break; case 3 : a+=k[0]&0xffffff; break; case 2 : a+=k[0]&0xffff; break; case 1 : a+=k[0]&0xff; break; case 0 : return c; /* zero length strings require no mixing */ } #else /* make valgrind happy */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]; break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ case 1 : a+=k8[0]; break; case 0 : return c; } #endif /* !valgrind */ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ const uint8_t *k8; /*--------------- all but last block: aligned reads and different mixing */ while (length > 12) { a += k[0] + (((uint32_t)k[1])<<16); b += k[2] + (((uint32_t)k[3])<<16); c += k[4] + (((uint32_t)k[5])<<16); mix(a,b,c); length -= 12; k += 6; } /*----------------------------- handle the last (probably partial) block */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[4]+(((uint32_t)k[5])<<16); b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=k[4]; b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=k[2]; a+=k[0]+(((uint32_t)k[1])<<16); break; case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]+(((uint32_t)k[1])<<16); break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=k[0]; break; case 1 : a+=k8[0]; break; case 0 : return c; /* zero length requires no mixing */ } } else { /* need to read the key one byte at a time */ const uint8_t *k = (const uint8_t *)key; /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; a += ((uint32_t)k[1])<<8; a += ((uint32_t)k[2])<<16; a += ((uint32_t)k[3])<<24; b += k[4]; b += ((uint32_t)k[5])<<8; b += ((uint32_t)k[6])<<16; b += ((uint32_t)k[7])<<24; c += k[8]; c += ((uint32_t)k[9])<<8; c += ((uint32_t)k[10])<<16; c += ((uint32_t)k[11])<<24; mix(a,b,c); length -= 12; k += 12; } /*-------------------------------- last block: affect all 32 bits of (c) */ switch(length) /* all the case statements fall through */ { case 12: c+=((uint32_t)k[11])<<24; /* fallthrough */ case 11: c+=((uint32_t)k[10])<<16; /* fallthrough */ case 10: c+=((uint32_t)k[9])<<8; /* fallthrough */ case 9 : c+=k[8]; /* fallthrough */ case 8 : b+=((uint32_t)k[7])<<24; /* fallthrough */ case 7 : b+=((uint32_t)k[6])<<16; /* fallthrough */ case 6 : b+=((uint32_t)k[5])<<8; /* fallthrough */ case 5 : b+=k[4]; /* fallthrough */ case 4 : a+=((uint32_t)k[3])<<24; /* fallthrough */ case 3 : a+=((uint32_t)k[2])<<16; /* fallthrough */ case 2 : a+=((uint32_t)k[1])<<8; /* fallthrough */ case 1 : a+=k[0]; break; case 0 : return c; } } final(a,b,c); return c; } #ifdef SELF_TEST /* * hashlittle2: return 2 32-bit hash values * * This is identical to hashlittle(), except it returns two 32-bit hash * values instead of just one. This is good enough for hash table * lookup with 2^^64 buckets, or if you want a second hash if you're not * happy with the first, or if you want a probably-unique 64-bit ID for * the key. *pc is better mixed than *pb, so use *pc first. If you want * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)". */ void hashlittle2( const void *key, /* the key to hash */ size_t length, /* length of the key */ uint32_t *pc, /* IN: primary initval, OUT: primary hash */ uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */ { uint32_t a,b,c; /* internal state */ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ /* Set up the internal state */ a = b = c = raninit + ((uint32_t)length) + *pc; c += *pb; u.ptr = key; if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ #ifdef VALGRIND const uint8_t *k8; #endif /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 12; k += 3; } /*----------------------------- handle the last (probably partial) block */ /* * "k[2]&0xffffff" actually reads beyond the end of the string, but * then masks off the part it's not allowed to read. Because the * string is aligned, the masked-off tail is in the same word as the * rest of the string. Every machine with memory protection I've seen * does it on word boundaries, so is OK with this. But VALGRIND will * still catch it and complain. The masking trick does make the hash * noticeably faster for short strings (like English words). */ #ifndef VALGRIND switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=k[1]&0xffffff; a+=k[0]; break; case 6 : b+=k[1]&0xffff; a+=k[0]; break; case 5 : b+=k[1]&0xff; a+=k[0]; break; case 4 : a+=k[0]; break; case 3 : a+=k[0]&0xffffff; break; case 2 : a+=k[0]&0xffff; break; case 1 : a+=k[0]&0xff; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } #else /* make valgrind happy */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]; break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ case 1 : a+=k8[0]; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } #endif /* !valgrind */ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ const uint8_t *k8; /*--------------- all but last block: aligned reads and different mixing */ while (length > 12) { a += k[0] + (((uint32_t)k[1])<<16); b += k[2] + (((uint32_t)k[3])<<16); c += k[4] + (((uint32_t)k[5])<<16); mix(a,b,c); length -= 12; k += 6; } /*----------------------------- handle the last (probably partial) block */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[4]+(((uint32_t)k[5])<<16); b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=k[4]; b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=k[2]; a+=k[0]+(((uint32_t)k[1])<<16); break; case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]+(((uint32_t)k[1])<<16); break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=k[0]; break; case 1 : a+=k8[0]; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } } else { /* need to read the key one byte at a time */ const uint8_t *k = (const uint8_t *)key; /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; a += ((uint32_t)k[1])<<8; a += ((uint32_t)k[2])<<16; a += ((uint32_t)k[3])<<24; b += k[4]; b += ((uint32_t)k[5])<<8; b += ((uint32_t)k[6])<<16; b += ((uint32_t)k[7])<<24; c += k[8]; c += ((uint32_t)k[9])<<8; c += ((uint32_t)k[10])<<16; c += ((uint32_t)k[11])<<24; mix(a,b,c); length -= 12; k += 12; } /*-------------------------------- last block: affect all 32 bits of (c) */ switch(length) /* all the case statements fall through */ { case 12: c+=((uint32_t)k[11])<<24; case 11: c+=((uint32_t)k[10])<<16; case 10: c+=((uint32_t)k[9])<<8; case 9 : c+=k[8]; case 8 : b+=((uint32_t)k[7])<<24; case 7 : b+=((uint32_t)k[6])<<16; case 6 : b+=((uint32_t)k[5])<<8; case 5 : b+=k[4]; case 4 : a+=((uint32_t)k[3])<<24; case 3 : a+=((uint32_t)k[2])<<16; case 2 : a+=((uint32_t)k[1])<<8; case 1 : a+=k[0]; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } } final(a,b,c); *pc=c; *pb=b; } #endif /* SELF_TEST */ #if 0 /* currently not used */ /* * hashbig(): * This is the same as hashword() on big-endian machines. It is different * from hashlittle() on all machines. hashbig() takes advantage of * big-endian byte ordering. */ uint32_t hashbig( const void *key, size_t length, uint32_t initval) { uint32_t a,b,c; union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */ /* Set up the internal state */ a = b = c = raninit + ((uint32_t)length) + initval; u.ptr = key; if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) { const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ #ifdef VALGRIND const uint8_t *k8; #endif /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 12; k += 3; } /*----------------------------- handle the last (probably partial) block */ /* * "k[2]<<8" actually reads beyond the end of the string, but * then shifts out the part it's not allowed to read. Because the * string is aligned, the illegal read is in the same word as the * rest of the string. Every machine with memory protection I've seen * does it on word boundaries, so is OK with this. But VALGRIND will * still catch it and complain. The masking trick does make the hash * noticeably faster for short strings (like English words). */ #ifndef VALGRIND switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break; case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break; case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=k[1]&0xffffff00; a+=k[0]; break; case 6 : b+=k[1]&0xffff0000; a+=k[0]; break; case 5 : b+=k[1]&0xff000000; a+=k[0]; break; case 4 : a+=k[0]; break; case 3 : a+=k[0]&0xffffff00; break; case 2 : a+=k[0]&0xffff0000; break; case 1 : a+=k[0]&0xff000000; break; case 0 : return c; /* zero length strings require no mixing */ } #else /* make valgrind happy */ k8 = (const uint8_t *)k; switch(length) /* all the case statements fall through */ { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=((uint32_t)k8[10])<<8; /* fall through */ case 10: c+=((uint32_t)k8[9])<<16; /* fall through */ case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */ case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */ case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */ case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */ case 4 : a+=k[0]; break; case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */ case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */ case 1 : a+=((uint32_t)k8[0])<<24; break; case 0 : return c; } #endif /* !VALGRIND */ } else { /* need to read the key one byte at a time */ const uint8_t *k = (const uint8_t *)key; /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ while (length > 12) { a += ((uint32_t)k[0])<<24; a += ((uint32_t)k[1])<<16; a += ((uint32_t)k[2])<<8; a += ((uint32_t)k[3]); b += ((uint32_t)k[4])<<24; b += ((uint32_t)k[5])<<16; b += ((uint32_t)k[6])<<8; b += ((uint32_t)k[7]); c += ((uint32_t)k[8])<<24; c += ((uint32_t)k[9])<<16; c += ((uint32_t)k[10])<<8; c += ((uint32_t)k[11]); mix(a,b,c); length -= 12; k += 12; } /*-------------------------------- last block: affect all 32 bits of (c) */ switch(length) /* all the case statements fall through */ { case 12: c+=k[11]; case 11: c+=((uint32_t)k[10])<<8; case 10: c+=((uint32_t)k[9])<<16; case 9 : c+=((uint32_t)k[8])<<24; case 8 : b+=k[7]; case 7 : b+=((uint32_t)k[6])<<8; case 6 : b+=((uint32_t)k[5])<<16; case 5 : b+=((uint32_t)k[4])<<24; case 4 : a+=k[3]; case 3 : a+=((uint32_t)k[2])<<8; case 2 : a+=((uint32_t)k[1])<<16; case 1 : a+=((uint32_t)k[0])<<24; break; case 0 : return c; } } final(a,b,c); return c; } #endif /* 0 == currently not used */ #ifdef SELF_TEST /* used for timings */ void driver1(void) { uint8_t buf[256]; uint32_t i; uint32_t h=0; time_t a,z; time(&a); for (i=0; i<256; ++i) buf[i] = 'x'; for (i=0; i<1; ++i) { h = hashlittle(&buf[0],1,h); } time(&z); if (z-a > 0) printf("time %d %.8x\n", z-a, h); } /* check that every input bit changes every output bit half the time */ #define HASHSTATE 1 #define HASHLEN 1 #define MAXPAIR 60 #define MAXLEN 70 void driver2(void) { uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1]; uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z; uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE]; uint32_t x[HASHSTATE],y[HASHSTATE]; uint32_t hlen; printf("No more than %d trials should ever be needed \n",MAXPAIR/2); for (hlen=0; hlen < MAXLEN; ++hlen) { z=0; for (i=0; i>(8-j)); c[0] = hashlittle(a, hlen, m); b[i] ^= ((k+1)<>(8-j)); d[0] = hashlittle(b, hlen, m); /* check every bit is 1, 0, set, and not set at least once */ for (l=0; lz) z=k; if (k==MAXPAIR) { printf("Some bit didn't change: "); printf("%.8x %.8x %.8x %.8x %.8x %.8x ", e[0],f[0],g[0],h[0],x[0],y[0]); printf("i %d j %d m %d len %d\n", i, j, m, hlen); } if (z==MAXPAIR) goto done; } } } done: if (z < MAXPAIR) { printf("Mix success %2d bytes %2d initvals ",i,m); printf("required %d trials\n", z/2); } } printf("\n"); } /* Check for reading beyond the end of the buffer and alignment problems */ void driver3(void) { uint8_t buf[MAXLEN+20], *b; uint32_t len; uint8_t q[] = "This is the time for all good men to come to the aid of their country..."; uint32_t h; uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country..."; uint32_t i; uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country..."; uint32_t j; uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country..."; uint32_t ref,x,y; uint8_t *p; printf("Endianness. These lines should all be the same (for values filled in):\n"); printf("%.8x %.8x %.8x\n", hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13), hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13), hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13)); p = q; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); p = &qq[1]; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); p = &qqq[2]; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); p = &qqqq[3]; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); printf("\n"); /* check that hashlittle2 and hashlittle produce the same results */ i=47; j=0; hashlittle2(q, sizeof(q), &i, &j); if (hashlittle(q, sizeof(q), 47) != i) printf("hashlittle2 and hashlittle mismatch\n"); /* check that hashword2 and hashword produce the same results */ len = raninit; i=47, j=0; hashword2(&len, 1, &i, &j); if (hashword(&len, 1, 47) != i) printf("hashword2 and hashword mismatch %x %x\n", i, hashword(&len, 1, 47)); /* check hashlittle doesn't read before or after the ends of the string */ for (h=0, b=buf+1; h<8; ++h, ++b) { for (i=0; ikey is deleted immediately. * But entry->data is set to NULL before deletion, and put into * the existing entry. The data is then freed. * @param data: the data. * @param cb_override: if not null overrides the cb_arg for the deletefunc. */ void lruhash_insert(struct lruhash* table, hashvalue_type hash, struct lruhash_entry* entry, void* data, void* cb_override); /** * Lookup an entry in the hashtable. * At the end of the function you hold a (read/write)lock on the entry. * The LRU is updated for the entry (if found). * @param table: hash table. * @param hash: hash of key. * @param key: what to look for, compared against entries in overflow chain. * the hash value must be set, and must work with compare function. * @param wr: set to true if you desire a writelock on the entry. * with a writelock you can update the data part. * @return: pointer to the entry or NULL. The entry is locked. * The user must unlock the entry when done. */ struct lruhash_entry* lruhash_lookup(struct lruhash* table, hashvalue_type hash, void* key, int wr); /** * Touch entry, so it becomes the most recently used in the LRU list. * Caller must hold hash table lock. The entry must be inserted already. * @param table: hash table. * @param entry: entry to make first in LRU. */ void lru_touch(struct lruhash* table, struct lruhash_entry* entry); /** * Set the markdelfunction (or NULL) */ void lruhash_setmarkdel(struct lruhash* table, lruhash_markdelfunc_type md); /************************* getdns functions ************************/ /*** these are used by getdns only and not by unbound. ***/ /** * Demote entry, so it becomes the least recently used in the LRU list. * Caller must hold hash table lock. The entry must be inserted already. * @param table: hash table. * @param entry: entry to make last in LRU. */ void lru_demote(struct lruhash* table, struct lruhash_entry* entry); /** * Insert a new element into the hashtable, or retrieve the corresponding * element of it exits. * * If key is already present data pointer in that entry is kept. * If it is not present, a new entry is created. In that case, * the space calculation function is called with the key, data. * If necessary the least recently used entries are deleted to make space. * If necessary the hash array is grown up. * * @param table: hash table. * @param hash: hash value. User calculates the hash. * @param entry: identifies the entry. * @param data: the data. * @param cb_arg: if not null overrides the cb_arg for the deletefunc. * @return: pointer to the existing entry if the key was already present, * or to the entry argument if it was not. */ struct lruhash_entry* lruhash_insert_or_retrieve(struct lruhash* table, hashvalue_type hash, struct lruhash_entry* entry, void* data, void* cb_arg); /************************* Internal functions ************************/ /*** these are only exposed for unit tests. ***/ /** * Remove entry from hashtable. Does nothing if not found in hashtable. * Delfunc is called for the entry. * @param table: hash table. * @param hash: hash of key. * @param key: what to look for. */ void lruhash_remove(struct lruhash* table, hashvalue_type hash, void* key); /** init the hash bins for the table */ void bin_init(struct lruhash_bin* array, size_t size); /** delete the hash bin and entries inside it */ void bin_delete(struct lruhash* table, struct lruhash_bin* bin); /** * Find entry in hash bin. You must have locked the bin. * @param table: hash table with function pointers. * @param bin: hash bin to look into. * @param hash: hash value to look for. * @param key: key to look for. * @return: the entry or NULL if not found. */ struct lruhash_entry* bin_find_entry(struct lruhash* table, struct lruhash_bin* bin, hashvalue_type hash, void* key); /** * Remove entry from bin overflow chain. * You must have locked the bin. * @param bin: hash bin to look into. * @param entry: entry ptr that needs removal. */ void bin_overflow_remove(struct lruhash_bin* bin, struct lruhash_entry* entry); /** * Split hash bin into two new ones. Based on increased size_mask. * Caller must hold hash table lock. * At the end the routine acquires all hashbin locks (in the old array). * This makes it wait for other threads to finish with the bins. * So the bins are ready to be deleted after this function. * @param table: hash table with function pointers. * @param newa: new increased array. * @param newmask: new lookup mask. */ void bin_split(struct lruhash* table, struct lruhash_bin* newa, int newmask); /** * Try to make space available by deleting old entries. * Assumes that the lock on the hashtable is being held by caller. * Caller must not hold bin locks. * @param table: hash table. * @param list: list of entries that are to be deleted later. * Entries have been removed from the hash table and writelock is held. */ void reclaim_space(struct lruhash* table, struct lruhash_entry** list); /** * Grow the table lookup array. Becomes twice as large. * Caller must hold the hash table lock. Must not hold any bin locks. * Tries to grow, on malloc failure, nothing happened. * @param table: hash table. */ void table_grow(struct lruhash* table); /** * Put entry at front of lru. entry must be unlinked from lru. * Caller must hold hash table lock. * @param table: hash table with lru head and tail. * @param entry: entry to make most recently used. */ void lru_front(struct lruhash* table, struct lruhash_entry* entry); /** * Remove entry from lru list. * Caller must hold hash table lock. * @param table: hash table with lru head and tail. * @param entry: entry to remove from lru. */ void lru_remove(struct lruhash* table, struct lruhash_entry* entry); /** * Output debug info to the log as to state of the hash table. * @param table: hash table. * @param id: string printed with table to identify the hash table. * @param extended: set to true to print statistics on overflow bin lengths. */ void lruhash_status(struct lruhash* table, const char* id, int extended); /** * Get memory in use now by the lruhash table. * @param table: hash table. Will be locked before use. And unlocked after. * @return size in bytes. */ size_t lruhash_get_mem(struct lruhash* table); /** * Traverse a lruhash. Call back for every element in the table. * @param h: hash table. Locked before use. * @param wr: if true writelock is obtained on element, otherwise readlock. * @param func: function for every element. Do not lock or unlock elements. * @param arg: user argument to func. */ void lruhash_traverse(struct lruhash* h, int wr, void (*func)(struct lruhash_entry*, void*), void* arg); #endif /* UTIL_STORAGE_LRUHASH_H */ getdns-1.5.1/src/util/orig-headers/lookup3.h0000644000175000017500000000517713416117763015630 00000000000000/* * util/storage/lookup3.h - header file for hashing functions. * * Copyright (c) 2007, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. */ /** * \file * * This file contains header definitions for the hash functions we use. * The hash functions are public domain (see lookup3.c). */ #ifndef UTIL_STORAGE_LOOKUP3_H #define UTIL_STORAGE_LOOKUP3_H /** * Hash key made of 4byte chunks. * @param k: the key, an array of uint32_t values * @param length: the length of the key, in uint32_ts * @param initval: the previous hash, or an arbitrary value * @return: hash value. */ uint32_t hashword(const uint32_t *k, size_t length, uint32_t initval); /** * Hash key data. * @param k: the key, array of uint8_t * @param length: the length of the key, in uint8_ts * @param initval: the previous hash, or an arbitrary value * @return: hash value. */ uint32_t hashlittle(const void *k, size_t length, uint32_t initval); /** * Set the randomisation initial value, set this before threads start, * and before hashing stuff (because it changes subsequent results). * @param v: value */ void hash_set_raninit(uint32_t v); #endif /* UTIL_STORAGE_LOOKUP3_H */ getdns-1.5.1/src/util/orig-headers/rbtree.h0000644000175000017500000001436613416117763015517 00000000000000/* * rbtree.h -- generic red-black tree * * Copyright (c) 2001-2007, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. * */ /** * \file * Red black tree. Implementation taken from NSD 3.0.5, adjusted for use * in unbound (memory allocation, logging and so on). */ #ifndef UTIL_RBTREE_H_ #define UTIL_RBTREE_H_ /** * This structure must be the first member of the data structure in * the rbtree. This allows easy casting between an rbnode_type and the * user data (poor man's inheritance). */ typedef struct rbnode_type rbnode_type; /** * The rbnode_type struct definition. */ struct rbnode_type { /** parent in rbtree, RBTREE_NULL for root */ rbnode_type *parent; /** left node (smaller items) */ rbnode_type *left; /** right node (larger items) */ rbnode_type *right; /** pointer to sorting key */ const void *key; /** colour of this node */ uint8_t color; }; /** The nullpointer, points to empty node */ #define RBTREE_NULL &rbtree_null_node /** the global empty node */ extern rbnode_type rbtree_null_node; /** An entire red black tree */ typedef struct rbtree_type rbtree_type; /** definition for tree struct */ struct rbtree_type { /** The root of the red-black tree */ rbnode_type *root; /** The number of the nodes in the tree */ size_t count; /** * Key compare function. <0,0,>0 like strcmp. * Return 0 on two NULL ptrs. */ int (*cmp) (const void *, const void *); }; /** * Create new tree (malloced) with given key compare function. * @param cmpf: compare function (like strcmp) takes pointers to two keys. * @return: new tree, empty. */ rbtree_type *rbtree_create(int (*cmpf)(const void *, const void *)); /** * Init a new tree (malloced by caller) with given key compare function. * @param rbtree: uninitialised memory for new tree, returned empty. * @param cmpf: compare function (like strcmp) takes pointers to two keys. */ void rbtree_init(rbtree_type *rbtree, int (*cmpf)(const void *, const void *)); /** * Insert data into the tree. * @param rbtree: tree to insert to. * @param data: element to insert. * @return: data ptr or NULL if key already present. */ rbnode_type *rbtree_insert(rbtree_type *rbtree, rbnode_type *data); /** * Delete element from tree. * @param rbtree: tree to delete from. * @param key: key of item to delete. * @return: node that is now unlinked from the tree. User to delete it. * returns 0 if node not present */ rbnode_type *rbtree_delete(rbtree_type *rbtree, const void *key); /** * Find key in tree. Returns NULL if not found. * @param rbtree: tree to find in. * @param key: key that must match. * @return: node that fits or NULL. */ rbnode_type *rbtree_search(rbtree_type *rbtree, const void *key); /** * Find, but match does not have to be exact. * @param rbtree: tree to find in. * @param key: key to find position of. * @param result: set to the exact node if present, otherwise to element that * precedes the position of key in the tree. NULL if no smaller element. * @return: true if exact match in result. Else result points to <= element, * or NULL if key is smaller than the smallest key. */ int rbtree_find_less_equal(rbtree_type *rbtree, const void *key, rbnode_type **result); /** * Returns first (smallest) node in the tree * @param rbtree: tree * @return: smallest element or NULL if tree empty. */ rbnode_type *rbtree_first(const rbtree_type *rbtree); /** * Returns last (largest) node in the tree * @param rbtree: tree * @return: largest element or NULL if tree empty. */ rbnode_type *rbtree_last(rbtree_type *rbtree); /** * Returns next larger node in the tree * @param rbtree: tree * @return: next larger element or NULL if no larger in tree. */ rbnode_type *rbtree_next(rbnode_type *rbtree); /** * Returns previous smaller node in the tree * @param rbtree: tree * @return: previous smaller element or NULL if no previous in tree. */ rbnode_type *rbtree_previous(rbnode_type *rbtree); /** * Call with node=variable of struct* with rbnode_type as first element. * with type is the type of a pointer to that struct. */ #define RBTREE_FOR(node, type, rbtree) \ for(node=(type)rbtree_first(rbtree); \ (rbnode_type*)node != RBTREE_NULL; \ node = (type)rbtree_next((rbnode_type*)node)) /** * Call function for all elements in the redblack tree, such that * leaf elements are called before parent elements. So that all * elements can be safely free()d. * Note that your function must not remove the nodes from the tree. * Since that may trigger rebalances of the rbtree. * @param tree: the tree * @param func: function called with element and user arg. * The function must not alter the rbtree. * @param arg: user argument. */ void traverse_postorder(rbtree_type* tree, void (*func)(rbnode_type*, void*), void* arg); #endif /* UTIL_RBTREE_H_ */ getdns-1.5.1/src/util/orig-headers/locks.h0000644000175000017500000003103613416117763015340 00000000000000/** * util/locks.h - unbound locking primitives * * Copyright (c) 2007, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. */ #ifndef UTIL_LOCKS_H #define UTIL_LOCKS_H /** * \file * Locking primitives. * If pthreads is available, these are used. * If no locking exists, they do nothing. * * The idea is to have different sorts of locks for different tasks. * This allows the locking code to be ported more easily. * * Types of locks that are supported. * o lock_rw: lock that has many readers and one writer (to a data entry). * o lock_basic: simple mutex. Blocking, one person has access only. * This lock is meant for non performance sensitive uses. * o lock_quick: speed lock. For performance sensitive locking of critical * sections. Could be implemented by a mutex or a spinlock. * * Also thread creation and deletion functions are defined here. */ /* if you define your own LOCKRET before including locks.h, you can get most * locking functions without the dependency on log_err. */ #ifndef LOCKRET #include "util/log.h" /** * The following macro is used to check the return value of the * pthread calls. They return 0 on success and an errno on error. * The errno is logged to the logfile with a descriptive comment. */ #define LOCKRET(func) do {\ int lockret_err; \ if( (lockret_err=(func)) != 0) \ log_err("%s at %d could not " #func ": %s", \ __FILE__, __LINE__, strerror(lockret_err)); \ } while(0) #endif /** DEBUG: use thread debug whenever possible */ #if defined(HAVE_PTHREAD) && defined(HAVE_PTHREAD_SPINLOCK_T) && defined(ENABLE_LOCK_CHECKS) # define USE_THREAD_DEBUG #endif #ifdef USE_THREAD_DEBUG /******************* THREAD DEBUG ************************/ /* (some) checking; to detect races and deadlocks. */ #include "testcode/checklocks.h" #else /* USE_THREAD_DEBUG */ #define lock_protect(lock, area, size) /* nop */ #define lock_unprotect(lock, area) /* nop */ #define lock_get_mem(lock) (0) /* nothing */ #define checklock_start() /* nop */ #define checklock_stop() /* nop */ #ifdef HAVE_PTHREAD #include /******************* PTHREAD ************************/ /** use pthread mutex for basic lock */ typedef pthread_mutex_t lock_basic_type; /** small front for pthread init func, NULL is default attrs. */ #define lock_basic_init(lock) LOCKRET(pthread_mutex_init(lock, NULL)) #define lock_basic_destroy(lock) LOCKRET(pthread_mutex_destroy(lock)) #define lock_basic_lock(lock) LOCKRET(pthread_mutex_lock(lock)) #define lock_basic_unlock(lock) LOCKRET(pthread_mutex_unlock(lock)) #ifndef HAVE_PTHREAD_RWLOCK_T /** in case rwlocks are not supported, use a mutex. */ typedef pthread_mutex_t lock_rw_type; #define lock_rw_init(lock) LOCKRET(pthread_mutex_init(lock, NULL)) #define lock_rw_destroy(lock) LOCKRET(pthread_mutex_destroy(lock)) #define lock_rw_rdlock(lock) LOCKRET(pthread_mutex_lock(lock)) #define lock_rw_wrlock(lock) LOCKRET(pthread_mutex_lock(lock)) #define lock_rw_unlock(lock) LOCKRET(pthread_mutex_unlock(lock)) #else /* HAVE_PTHREAD_RWLOCK_T */ /** we use the pthread rwlock */ typedef pthread_rwlock_t lock_rw_type; /** small front for pthread init func, NULL is default attrs. */ #define lock_rw_init(lock) LOCKRET(pthread_rwlock_init(lock, NULL)) #define lock_rw_destroy(lock) LOCKRET(pthread_rwlock_destroy(lock)) #define lock_rw_rdlock(lock) LOCKRET(pthread_rwlock_rdlock(lock)) #define lock_rw_wrlock(lock) LOCKRET(pthread_rwlock_wrlock(lock)) #define lock_rw_unlock(lock) LOCKRET(pthread_rwlock_unlock(lock)) #endif /* HAVE_PTHREAD_RWLOCK_T */ #ifndef HAVE_PTHREAD_SPINLOCK_T /** in case spinlocks are not supported, use a mutex. */ typedef pthread_mutex_t lock_quick_type; /** small front for pthread init func, NULL is default attrs. */ #define lock_quick_init(lock) LOCKRET(pthread_mutex_init(lock, NULL)) #define lock_quick_destroy(lock) LOCKRET(pthread_mutex_destroy(lock)) #define lock_quick_lock(lock) LOCKRET(pthread_mutex_lock(lock)) #define lock_quick_unlock(lock) LOCKRET(pthread_mutex_unlock(lock)) #else /* HAVE_PTHREAD_SPINLOCK_T */ /** use pthread spinlock for the quick lock */ typedef pthread_spinlock_t lock_quick_type; /** * allocate process private since this is available whether * Thread Process-Shared Synchronization is supported or not. * This means only threads inside this process may access the lock. * (not threads from another process that shares memory). * spinlocks are not supported on all pthread platforms. */ #define lock_quick_init(lock) LOCKRET(pthread_spin_init(lock, PTHREAD_PROCESS_PRIVATE)) #define lock_quick_destroy(lock) LOCKRET(pthread_spin_destroy(lock)) #define lock_quick_lock(lock) LOCKRET(pthread_spin_lock(lock)) #define lock_quick_unlock(lock) LOCKRET(pthread_spin_unlock(lock)) #endif /* HAVE SPINLOCK */ /** Thread creation */ typedef pthread_t ub_thread_type; /** On alpine linux default thread stack size is 80 Kb. See http://wiki.musl-libc.org/wiki/Functional_differences_from_glibc#Thread_stack_size This is not enough and cause segfault. Other linux distros have 2 Mb at least. Wrapper for set up thread stack size */ #define PTHREADSTACKSIZE 2*1024*1024 #define PTHREADCREATE(thr, stackrequired, func, arg) do {\ pthread_attr_t attr; \ size_t stacksize; \ LOCKRET(pthread_attr_init(&attr)); \ LOCKRET(pthread_attr_getstacksize(&attr, &stacksize)); \ if (stacksize < stackrequired) { \ LOCKRET(pthread_attr_setstacksize(&attr, stackrequired)); \ LOCKRET(pthread_create(thr, &attr, func, arg)); \ LOCKRET(pthread_attr_getstacksize(&attr, &stacksize)); \ verbose(VERB_ALGO, "Thread stack size set to %u", (unsigned)stacksize); \ } else {LOCKRET(pthread_create(thr, NULL, func, arg));} \ } while(0) /** Use wrapper for set thread stack size on attributes. */ #define ub_thread_create(thr, func, arg) PTHREADCREATE(thr, PTHREADSTACKSIZE, func, arg) /** get self id. */ #define ub_thread_self() pthread_self() /** wait for another thread to terminate */ #define ub_thread_join(thread) LOCKRET(pthread_join(thread, NULL)) typedef pthread_key_t ub_thread_key_type; #define ub_thread_key_create(key, f) LOCKRET(pthread_key_create(key, f)) #define ub_thread_key_set(key, v) LOCKRET(pthread_setspecific(key, v)) #define ub_thread_key_get(key) pthread_getspecific(key) #else /* we do not HAVE_PTHREAD */ #ifdef HAVE_SOLARIS_THREADS /******************* SOLARIS THREADS ************************/ #include #include typedef rwlock_t lock_rw_type; #define lock_rw_init(lock) LOCKRET(rwlock_init(lock, USYNC_THREAD, NULL)) #define lock_rw_destroy(lock) LOCKRET(rwlock_destroy(lock)) #define lock_rw_rdlock(lock) LOCKRET(rw_rdlock(lock)) #define lock_rw_wrlock(lock) LOCKRET(rw_wrlock(lock)) #define lock_rw_unlock(lock) LOCKRET(rw_unlock(lock)) /** use basic mutex */ typedef mutex_t lock_basic_type; #define lock_basic_init(lock) LOCKRET(mutex_init(lock, USYNC_THREAD, NULL)) #define lock_basic_destroy(lock) LOCKRET(mutex_destroy(lock)) #define lock_basic_lock(lock) LOCKRET(mutex_lock(lock)) #define lock_basic_unlock(lock) LOCKRET(mutex_unlock(lock)) /** No spinlocks in solaris threads API. Use a mutex. */ typedef mutex_t lock_quick_type; #define lock_quick_init(lock) LOCKRET(mutex_init(lock, USYNC_THREAD, NULL)) #define lock_quick_destroy(lock) LOCKRET(mutex_destroy(lock)) #define lock_quick_lock(lock) LOCKRET(mutex_lock(lock)) #define lock_quick_unlock(lock) LOCKRET(mutex_unlock(lock)) /** Thread creation, create a default thread. */ typedef thread_t ub_thread_type; #define ub_thread_create(thr, func, arg) LOCKRET(thr_create(NULL, NULL, func, arg, NULL, thr)) #define ub_thread_self() thr_self() #define ub_thread_join(thread) LOCKRET(thr_join(thread, NULL, NULL)) typedef thread_key_t ub_thread_key_type; #define ub_thread_key_create(key, f) LOCKRET(thr_keycreate(key, f)) #define ub_thread_key_set(key, v) LOCKRET(thr_setspecific(key, v)) void* ub_thread_key_get(ub_thread_key_type key); #else /* we do not HAVE_SOLARIS_THREADS and no PTHREADS */ /******************* WINDOWS THREADS ************************/ #ifdef HAVE_WINDOWS_THREADS #include /* Use a mutex */ typedef LONG lock_rw_type; #define lock_rw_init(lock) lock_basic_init(lock) #define lock_rw_destroy(lock) lock_basic_destroy(lock) #define lock_rw_rdlock(lock) lock_basic_lock(lock) #define lock_rw_wrlock(lock) lock_basic_lock(lock) #define lock_rw_unlock(lock) lock_basic_unlock(lock) /** the basic lock is a mutex, implemented opaquely, for error handling. */ typedef LONG lock_basic_type; void lock_basic_init(lock_basic_type* lock); void lock_basic_destroy(lock_basic_type* lock); void lock_basic_lock(lock_basic_type* lock); void lock_basic_unlock(lock_basic_type* lock); /** on windows no spinlock, use mutex too. */ typedef LONG lock_quick_type; #define lock_quick_init(lock) lock_basic_init(lock) #define lock_quick_destroy(lock) lock_basic_destroy(lock) #define lock_quick_lock(lock) lock_basic_lock(lock) #define lock_quick_unlock(lock) lock_basic_unlock(lock) /** Thread creation, create a default thread. */ typedef HANDLE ub_thread_type; void ub_thread_create(ub_thread_type* thr, void* (*func)(void*), void* arg); ub_thread_type ub_thread_self(void); void ub_thread_join(ub_thread_type thr); typedef DWORD ub_thread_key_type; void ub_thread_key_create(ub_thread_key_type* key, void* f); void ub_thread_key_set(ub_thread_key_type key, void* v); void* ub_thread_key_get(ub_thread_key_type key); #else /* we do not HAVE_SOLARIS_THREADS, PTHREADS or WINDOWS_THREADS */ /******************* NO THREADS ************************/ #define THREADS_DISABLED 1 /** In case there is no thread support, define locks to do nothing */ typedef int lock_rw_type; #define lock_rw_init(lock) /* nop */ #define lock_rw_destroy(lock) /* nop */ #define lock_rw_rdlock(lock) /* nop */ #define lock_rw_wrlock(lock) /* nop */ #define lock_rw_unlock(lock) /* nop */ /** define locks to do nothing */ typedef int lock_basic_type; #define lock_basic_init(lock) /* nop */ #define lock_basic_destroy(lock) /* nop */ #define lock_basic_lock(lock) /* nop */ #define lock_basic_unlock(lock) /* nop */ /** define locks to do nothing */ typedef int lock_quick_type; #define lock_quick_init(lock) /* nop */ #define lock_quick_destroy(lock) /* nop */ #define lock_quick_lock(lock) /* nop */ #define lock_quick_unlock(lock) /* nop */ /** Thread creation, threads do not exist */ typedef pid_t ub_thread_type; /** ub_thread_create is simulated with fork (extremely heavy threads, * with no shared memory). */ #define ub_thread_create(thr, func, arg) \ ub_thr_fork_create(thr, func, arg) #define ub_thread_self() getpid() #define ub_thread_join(thread) ub_thr_fork_wait(thread) void ub_thr_fork_wait(ub_thread_type thread); void ub_thr_fork_create(ub_thread_type* thr, void* (*func)(void*), void* arg); typedef void* ub_thread_key_type; #define ub_thread_key_create(key, f) (*(key)) = NULL #define ub_thread_key_set(key, v) (key) = (v) #define ub_thread_key_get(key) (key) #endif /* HAVE_WINDOWS_THREADS */ #endif /* HAVE_SOLARIS_THREADS */ #endif /* HAVE_PTHREAD */ #endif /* USE_THREAD_DEBUG */ /** * Block all signals for this thread. * fatal exit on error. */ void ub_thread_blocksigs(void); /** * unblock one signal for this thread. */ void ub_thread_sig_unblock(int sig); #endif /* UTIL_LOCKS_H */ getdns-1.5.1/src/util/orig-headers/val_secalgo.h0000644000175000017500000001001113416117763016472 00000000000000/* * validator/val_secalgo.h - validator security algorithm functions. * * Copyright (c) 2012, NLnet Labs. All rights reserved. * * This software is open source. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the NLNET LABS nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 COPYRIGHT * HOLDER OR CONTRIBUTORS 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. */ /** * \file * * This file contains helper functions for the validator module. * The functions take buffers with raw data and convert to library calls. */ #ifndef VALIDATOR_VAL_SECALGO_H #define VALIDATOR_VAL_SECALGO_H struct sldns_buffer; /** Return size of nsec3 hash algorithm, 0 if not supported */ size_t nsec3_hash_algo_size_supported(int id); /** * Hash a single hash call of an NSEC3 hash algorithm. * Iterations and salt are done by the caller. * @param algo: nsec3 hash algorithm. * @param buf: the buffer to digest * @param len: length of buffer to digest. * @param res: result stored here (must have sufficient space). * @return false on failure. */ int secalgo_nsec3_hash(int algo, unsigned char* buf, size_t len, unsigned char* res); /** * Calculate the sha256 hash for the data buffer into the result. * @param buf: buffer to digest. * @param len: length of the buffer to digest. * @param res: result is stored here (space 256/8 bytes). */ void secalgo_hash_sha256(unsigned char* buf, size_t len, unsigned char* res); /** * Return size of DS digest according to its hash algorithm. * @param algo: DS digest algo. * @return size in bytes of digest, or 0 if not supported. */ size_t ds_digest_size_supported(int algo); /** * @param algo: the DS digest algo * @param buf: the buffer to digest * @param len: length of buffer to digest. * @param res: result stored here (must have sufficient space). * @return false on failure. */ int secalgo_ds_digest(int algo, unsigned char* buf, size_t len, unsigned char* res); /** return true if DNSKEY algorithm id is supported */ int dnskey_algo_id_is_supported(int id); /** * Check a canonical sig+rrset and signature against a dnskey * @param buf: buffer with data to verify, the first rrsig part and the * canonicalized rrset. * @param algo: DNSKEY algorithm. * @param sigblock: signature rdata field from RRSIG * @param sigblock_len: length of sigblock data. * @param key: public key data from DNSKEY RR. * @param keylen: length of keydata. * @param reason: bogus reason in more detail. * @return secure if verification succeeded, bogus on crypto failure, * unchecked on format errors and alloc failures. */ enum sec_status verify_canonrrset(struct sldns_buffer* buf, int algo, unsigned char* sigblock, unsigned int sigblock_len, unsigned char* key, unsigned int keylen, char** reason); #endif /* VALIDATOR_VAL_SECALGO_H */ getdns-1.5.1/src/context.h0000644000175000017500000004550713416117763012373 00000000000000/** * * \file context.h * @brief getdns context management functions * * Originally taken from the getdns API description pseudo implementation. * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef _GETDNS_CONTEXT_H_ #define _GETDNS_CONTEXT_H_ #include "getdns/getdns.h" #include "getdns/getdns_extra.h" #include "config.h" #include "types-internal.h" #include "extension/default_eventloop.h" #include "util/rbtree.h" #include "ub_loop.h" #include "server.h" #ifdef HAVE_MDNS_SUPPORT #include "util/lruhash.h" #endif #include "rr-iter.h" #include "anchor.h" struct getdns_dns_req; struct ub_ctx; enum filechgs { GETDNS_FCHG_ERRORS = -1 , GETDNS_FCHG_NOERROR = 0 , GETDNS_FCHG_NOCHANGES = 0 , GETDNS_FCHG_MTIME = 1 , GETDNS_FCHG_CTIME = 2}; /** function pointer typedefs */ typedef void (*getdns_update_callback) (struct getdns_context *, getdns_context_code_t); typedef void (*getdns_update_callback2) (struct getdns_context *, getdns_context_code_t, void *userarg); /* internal use only for detecting changes to system files */ struct filechg { char fn[_GETDNS_PATH_MAX]; int changes; int errors; struct stat prevstat; }; typedef enum getdns_tls_hs_state { GETDNS_HS_NONE, GETDNS_HS_WRITE, GETDNS_HS_READ, GETDNS_HS_DONE, GETDNS_HS_FAILED } getdns_tls_hs_state_t; typedef enum getdns_conn_state { GETDNS_CONN_CLOSED, GETDNS_CONN_SETUP, GETDNS_CONN_OPEN, GETDNS_CONN_TEARDOWN, GETDNS_CONN_BACKOFF } getdns_conn_state_t; typedef enum getdns_tasrc { GETDNS_TASRC_NONE, GETDNS_TASRC_ZONE, GETDNS_TASRC_APP, GETDNS_TASRC_FETCHING, GETDNS_TASRC_XML, GETDNS_TASRC_XML_UPDATE, GETDNS_TASRC_FAILED } getdns_tasrc; typedef enum getdns_tsig_algo { GETDNS_NO_TSIG = 0, /* Do not use tsig */ GETDNS_HMAC_MD5 = 1, /* 128 bits */ GETDNS_GSS_TSIG = 2, /* Not supported */ GETDNS_HMAC_SHA1 = 3, /* 160 bits */ GETDNS_HMAC_SHA224 = 4, GETDNS_HMAC_SHA256 = 5, GETDNS_HMAC_SHA384 = 6, GETDNS_HMAC_SHA512 = 7 } getdns_tsig_algo; typedef struct getdns_tsig_info { getdns_tsig_algo alg; const char *name; size_t strlen_name; const uint8_t *dname; size_t dname_len; size_t min_size; /* in # octets */ size_t max_size; /* Actual size in # octets */ } getdns_tsig_info; const getdns_tsig_info *_getdns_get_tsig_info(getdns_tsig_algo tsig_alg); /* for doing public key pinning of TLS-capable upstreams: */ typedef struct sha256_pin { uint8_t pin[SHA256_DIGEST_LENGTH]; struct sha256_pin *next; } sha256_pin_t; typedef struct getdns_upstream { /* backpointer to containing upstreams structure */ struct getdns_upstreams *upstreams; socklen_t addr_len; struct sockaddr_storage addr; char addr_str[INET6_ADDRSTRLEN]; /** * How is this upstream doing over UDP? * * to_retry = 1, back_off = 1, in context.c:upstream_init() * * When querying over UDP, first a upstream is selected which to_retry * value > 0 in stub.c:upstream_select(). * * Every time a udp request times out, to_retry is decreased, and if * it reaches 0, it is set to minus back_off in * stub.c:stub_next_upstream(). * * to_retry will become > 0 again. because each time an upstream is * selected for a UDP query in stub.c:upstream_select(), all to_retry * counters <= 0 are incremented. * * On continuous failure, the stubs are less likely to be reselected, * because each time to_retry is set to minus back_off, in * stub.c:stub_next_upstream(), the back_off value is doubled. * * Finally, if all upstreams are failing, the upstreams with the * smallest back_off value will be selected, and the back_off value * decremented by one. */ int to_retry; /* (initialized to 1) */ int back_off; /* (initialized to 1) */ size_t udp_responses; size_t udp_timeouts; /* For stateful upstreams, need to share the connection and track the activity on the connection */ int fd; getdns_transport_list_t transport; getdns_eventloop_event event; getdns_eventloop *loop; getdns_tcp_state tcp; /* These are running totals or historical info */ size_t conn_completed; size_t conn_shutdowns; size_t conn_setup_failed; time_t conn_retry_time; uint16_t conn_backoff_interval; size_t conn_backoffs; size_t total_responses; size_t total_timeouts; getdns_auth_state_t best_tls_auth_state; getdns_auth_state_t last_tls_auth_state; /* These are per connection. */ getdns_conn_state_t conn_state; size_t queries_sent; size_t responses_received; size_t responses_timeouts; size_t keepalive_shutdown; uint64_t keepalive_timeout; int server_keepalive_received; /* Management of outstanding requests on stateful transports */ getdns_network_req *write_queue; getdns_network_req *write_queue_last; _getdns_rbtree_t netreq_by_query_id; /* TLS specific connection handling */ SSL* tls_obj; SSL_SESSION* tls_session; getdns_tls_hs_state_t tls_hs_state; getdns_auth_state_t tls_auth_state; unsigned tls_fallback_ok : 1; /* TLS settings */ char *tls_cipher_list; char *tls_ciphersuites; char *tls_curves_list; getdns_tls_version_t tls_min_version; getdns_tls_version_t tls_max_version; /* Auth credentials */ char tls_auth_name[256]; sha256_pin_t *tls_pubkey_pinset; /* When requests have been scheduled asynchronously on an upstream * that is kept open, and a synchronous call is then done with the * upstream before all scheduled requests have been answered, answers * for the asynchronous requests may be received on the open upstream. * Those cannot be processed immediately, because then asynchronous * callbacks will be fired as a side-effect. * * finished_dnsreqs is a list of dnsreqs for which answers have been * received during a synchronous request. They will be processed * when the asynchronous eventloop is run. For this the finished_event * will be scheduled to the registered asynchronous event loop with a * timeout of 1, so it will fire immediately (but not while scheduling) * when the asynchronous eventloop is run. */ getdns_dns_req *finished_dnsreqs; getdns_eventloop_event finished_event; unsigned is_sync_loop : 1; /* EDNS cookies */ uint32_t secret; uint8_t client_cookie[8]; uint8_t prev_client_cookie[8]; uint8_t server_cookie[32]; unsigned has_client_cookie : 1; unsigned has_prev_client_cookie : 1; unsigned has_server_cookie : 1; unsigned server_cookie_len : 5; /* TSIG */ uint8_t tsig_dname[256]; size_t tsig_dname_len; size_t tsig_size; uint8_t tsig_key[256]; getdns_tsig_algo tsig_alg; } getdns_upstream; typedef struct getdns_log_config { getdns_logfunc_type func; void *userarg; uint64_t system; getdns_loglevel_type level; } getdns_log_config; typedef struct getdns_upstreams { struct mem_funcs mf; size_t referenced; size_t count; size_t current_udp; size_t current_stateful; uint16_t max_backoff_value; uint16_t tls_backoff_time; uint16_t tls_connection_retries; getdns_log_config log; getdns_upstream upstreams[]; } getdns_upstreams; typedef enum tas_state { TAS_LOOKUP_ADDRESSES = 0, TAS_WRITE_GET_XML, TAS_READ_XML_HDR, TAS_READ_XML_DOC, TAS_WRITE_GET_PS7, TAS_READ_PS7_HDR, TAS_READ_PS7_DOC, TAS_DONE, TAS_RETRY, TAS_RETRY_GET_PS7, TAS_RETRY_PS7_HDR, TAS_RETRY_PS7_DOC, TAS_RETRY_DONE } tas_state; typedef enum _getdns_property { PROP_INHERIT = 0, PROP_UNKNOWN = 1, PROP_UNABLE = 2, PROP_ABLE = 3 } _getdns_property; typedef struct tas_connection { getdns_eventloop *loop; getdns_network_req *req; _getdns_rrset_spc rrset_spc; _getdns_rrset *rrset; _getdns_rrtype_iter rr_spc; _getdns_rrtype_iter *rr; int fd; getdns_eventloop_event event; tas_state state; getdns_tcp_state tcp; char *http; getdns_bindata xml; } tas_connection; struct getdns_context { /* Context values */ getdns_resolution_t resolution_type; getdns_namespace_t *namespaces; size_t namespace_count; uint64_t timeout; uint64_t idle_timeout; getdns_redirects_t follow_redirects; getdns_list *dns_root_servers; #if defined(HAVE_LIBUNBOUND) && !defined(HAVE_UB_CTX_SET_STUB) char root_servers_fn[FILENAME_MAX]; #endif getdns_append_name_t append_name; /* Suffix buffer containing a list of (length byte | dname) where * length bytes contains the length of the following dname. * The last dname should be the zero byte. */ const uint8_t *suffixes; /* Length of all suffixes in the suffix buffer */ size_t suffixes_len; uint8_t *trust_anchors; size_t trust_anchors_len; getdns_tasrc trust_anchors_source; tas_connection a; tas_connection aaaa; uint8_t tas_hdr_spc[512]; char *trust_anchors_url; char *trust_anchors_verify_CA; char *trust_anchors_verify_email; uint64_t trust_anchors_backoff_time; uint64_t trust_anchors_backoff_expiry; _getdns_ksks root_ksk; char *appdata_dir; _getdns_property can_write_appdata; char *tls_ca_path; char *tls_ca_file; char *tls_cipher_list; char *tls_ciphersuites; char *tls_curves_list; getdns_tls_version_t tls_min_version; getdns_tls_version_t tls_max_version; getdns_upstreams *upstreams; uint16_t limit_outstanding_queries; uint32_t dnssec_allowed_skew; getdns_tls_authentication_t tls_auth; /* What user requested for TLS*/ getdns_tls_authentication_t tls_auth_min; /* Derived minimum auth allowed*/ uint8_t round_robin_upstreams; uint16_t max_backoff_value; uint16_t tls_backoff_time; uint16_t tls_connection_retries; getdns_transport_list_t *dns_transports; size_t dns_transport_count; uint8_t edns_extended_rcode; uint8_t edns_version; uint8_t edns_do_bit; int edns_maximum_udp_payload_size; /* -1 is unset */ uint8_t edns_client_subnet_private; uint16_t tls_query_padding_blocksize; SSL_CTX* tls_ctx; getdns_update_callback update_callback; getdns_update_callback2 update_callback2; void *update_userarg; getdns_log_config log; int processing; int destroying; struct mem_funcs mf; struct mem_funcs my_mf; #ifdef HAVE_LIBUNBOUND /* The underlying contexts that do the real work */ struct ub_ctx *unbound_ctx; int unbound_ta_set; #ifdef HAVE_UNBOUND_EVENT_API _getdns_ub_loop ub_loop; #endif #endif /* A tree to hold local host information*/ _getdns_rbtree_t local_hosts; /* which resolution type the contexts are configured for * 0 means nothing set */ getdns_resolution_t resolution_type_set; /* * outbound requests -> transaction to getdns_dns_req */ _getdns_rbtree_t outbound_requests; /* network requests */ size_t netreqs_in_flight; _getdns_rbtree_t pending_netreqs; getdns_network_req *first_pending_netreq; getdns_eventloop_event pending_timeout_event; struct listen_set *server; /* Event loop extension. */ getdns_eventloop *extension; #ifdef HAVE_LIBUNBOUND getdns_eventloop_event ub_event; /* lock to prevent nested ub_event scheduling */ int ub_event_scheduling; #endif /* The default extension */ _getdns_default_eventloop default_eventloop; _getdns_default_eventloop sync_eventloop; /* request extension defaults */ getdns_dict *header; getdns_dict *add_opt_parameters; unsigned add_warning_for_bad_dns : 1; unsigned dnssec : 1; unsigned dnssec_return_all_statuses : 1; unsigned dnssec_return_full_validation_chain : 1; unsigned dnssec_return_only_secure : 1; unsigned dnssec_return_status : 1; unsigned dnssec_return_validation_chain : 1; #ifdef DNSSEC_ROADBLOCK_AVOIDANCE unsigned dnssec_roadblock_avoidance : 1; #endif unsigned edns_cookies : 1; unsigned return_api_information : 1; /* Not used */ unsigned return_both_v4_and_v6 : 1; unsigned return_call_reporting : 1; uint16_t specify_class; /* * Context for doing system queries. * For example to resolve data.iana.org or to resolver the addresses * of upstreams without specified addresses. */ getdns_context *sys_ctxt; /* List of dnsreqs that want to be notified when we have fetched a * trust anchor from data.iana.org. */ getdns_dns_req *ta_notify; /* * state data used to detect changes to the system config files */ struct filechg fchg_resolvconf; struct filechg fchg_hosts; uint8_t trust_anchors_spc[1024]; #ifdef USE_WINSOCK /* We need to run WSAStartup() to be able to use getaddrinfo() */ WSADATA wsaData; #endif /* MDNS */ #ifdef HAVE_MDNS_SUPPORT /* * If supporting MDNS, context may be instantiated either in basic mode * or in full mode. If working in extended mode, two multicast sockets are * left open, for IPv4 and IPv6. Data can be received on either socket. * The context also keeps a list of open queries, characterized by a * name and an RR type, and a list of received answers, characterized * by name, RR type and data value. */ int mdns_extended_support; /* 0 = no support, 1 = supported, 2 = initialization needed */ int mdns_connection_nb; /* typically 0 or 2 for IPv4 and IPv6 */ struct mdns_network_connection * mdns_connection; struct lruhash * mdns_cache; #endif /* HAVE_MDNS_SUPPORT */ }; /* getdns_context */ static inline int _getdns_check_log(const getdns_log_config *log, uint64_t system, getdns_loglevel_type level) { assert(log) ; return log->func && (log->system & system) && level <= log->level; } static inline void _getdns_log(const getdns_log_config *log, uint64_t system, getdns_loglevel_type level, const char *fmt, ...) { va_list args; if (!_getdns_check_log(log, system, level)) return; va_start(args, fmt); log->func(log->userarg, system, level, fmt, args); va_end(args); } static inline void _getdns_upstream_log(const getdns_upstream *up, uint64_t system, getdns_loglevel_type level, const char *fmt, ...) { va_list args; if (!up || !up->upstreams || !_getdns_check_log(&up->upstreams->log, system, level)) return; va_start(args, fmt); up->upstreams->log.func( up->upstreams->log.userarg, system, level, fmt, args); va_end(args); } /** internal functions **/ /** * Sets up the unbound contexts with stub or recursive behavior * if needed. * @param context previously initialized getdns_context * @return GETDNS_RETURN_GOOD on success */ getdns_return_t _getdns_context_prepare_for_resolution(getdns_context *context); /* Register a getdns_dns_req with context. * - Without pluggable unbound event API, * ub_fd() is scheduled when this was the first request. */ void _getdns_context_track_outbound_request(getdns_dns_req *dnsreq); /* Deregister getdns_dns_req from the context. * - Without pluggable unbound event API, * ub_fd() is scheduled when this was the first request. * - Potential timeout events will be cleared. * - All associated getdns_dns_reqs (to get the validation chain) * will be canceled. */ void _getdns_context_clear_outbound_request(getdns_dns_req *dnsreq); /* Cancels and frees a getdns_dns_req (without calling user callbacks) * - Deregisters getdns_dns_req with _getdns_context_clear_outbound_request() * - Cancels associated getdns_network_reqs * (by calling ub_cancel() or _getdns_cancel_stub_request()) * - Frees the getdns_dns_req */ void _getdns_context_cancel_request(getdns_dns_req *dnsreq); /* Calls user callback (with GETDNS_CALLBACK_TIMEOUT + response dict), then * cancels and frees the getdns_dns_req with _getdns_context_cancel_request() */ void _getdns_context_request_timed_out(getdns_dns_req *dnsreq); struct getdns_bindata *_getdns_bindata_copy( struct mem_funcs *mfs, size_t size, const uint8_t *data); void _getdns_bindata_destroy( struct mem_funcs *mfs, struct getdns_bindata *bindata); /* perform name resolution in /etc/hosts */ getdns_return_t _getdns_context_local_namespace_resolve( getdns_dns_req* req, struct getdns_dict **response); void _getdns_context_ub_read_cb(void *userarg); void _getdns_upstreams_dereference(getdns_upstreams *upstreams); void _getdns_upstream_shutdown(getdns_upstream *upstream); FILE *_getdns_context_get_priv_fp( const getdns_context *context, const char *fn); uint8_t *_getdns_context_get_priv_file(const getdns_context *context, const char *fn, uint8_t *buf, size_t buf_len, size_t *file_sz); int _getdns_context_write_priv_file(getdns_context *context, const char *fn, getdns_bindata *content); int _getdns_context_can_write_appdata(getdns_context *context); getdns_context *_getdns_context_get_sys_ctxt( getdns_context *context, getdns_eventloop *loop); #endif /* _GETDNS_CONTEXT_H_ */ getdns-1.5.1/src/list.c0000644000175000017500000004423013416117763011645 00000000000000/** * * /brief getdns list management functions * * This is the meat of the API * Originally taken from the getdns API description pseudo implementation. * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 #include #include "types-internal.h" #include "util-internal.h" #include "list.h" #include "dict.h" getdns_return_t _getdns_list_find(const getdns_list *list, const char *key, getdns_item **item) { const char *next; char *endptr; size_t index; getdns_item *i; if (*key == '/') { if (!(next = strchr(++key, '/'))) next = strchr(key, '\0'); } else next = strchr(key, '\0'); if (key[0] == '-' && next == key + 1) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; index = strtoul(key, &endptr, 10); if (!isdigit((int)*key) || endptr != next) /* Not a list index, so it was assumed */ return GETDNS_RETURN_WRONG_TYPE_REQUESTED; if (index >= list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; i = &list->items[index]; if (!*next) { *item = i; return GETDNS_RETURN_GOOD; } else switch (i->dtype) { case t_dict: return _getdns_dict_find(i->data.dict, next, item); case t_list: return _getdns_list_find(i->data.list, next, item); default : /* Trying to dereference a non list or dict */ return GETDNS_RETURN_NO_SUCH_LIST_ITEM; } } getdns_return_t _getdns_list_remove_name(getdns_list *list, const char *name) { const char *next, *key = name; char *endptr; size_t index; getdns_item *i; if (*key == '/') { if (!(next = strchr(++key, '/'))) next = strchr(key, '\0'); } else next = strchr(key, '\0'); if (key[0] == '-' && next == key + 1) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; index = strtoul(key, &endptr, 10); if (!isdigit((int)*key) || endptr != next) /* Not a list index, so it was assumed */ return GETDNS_RETURN_WRONG_TYPE_REQUESTED; if (index >= list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; i = &list->items[index]; if (!*next) { switch (i->dtype) { case t_dict : getdns_dict_destroy(i->data.dict); break; case t_list : getdns_list_destroy(i->data.list); break; case t_bindata: _getdns_bindata_destroy( &list->mf, i->data.bindata); default : break; } if (index < list->numinuse - 1) (void) memmove( i, &i[1], (list->numinuse - index) * sizeof(getdns_item)); list->numinuse -= 1; return GETDNS_RETURN_GOOD; } else switch (i->dtype) { case t_dict: return getdns_dict_remove_name(i->data.dict, next); case t_list: return _getdns_list_remove_name(i->data.list, next); default : /* Trying to dereference a non list or dict */ return GETDNS_RETURN_NO_SUCH_LIST_ITEM; } } getdns_return_t _getdns_list_find_and_add( getdns_list *list, const char *key, getdns_item **item) { const char *next; char *endptr; size_t index; getdns_item *newlist, *i; if (*key == '/') { if (!(next = strchr(++key, '/'))) next = strchr(key, '\0'); } else next = strchr(key, '\0'); if (key[0] == '-' && next == key + 1) index = list->numinuse; else { index = strtoul(key, &endptr, 10); if (!isdigit((int)*key) || endptr != next) /* Not a list index, so it was assumed */ return GETDNS_RETURN_WRONG_TYPE_REQUESTED; } if (index > list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; if (index == list->numinuse) { if (list->numalloc <= list->numinuse) { if (!(newlist = GETDNS_XREALLOC(list->mf, list->items, getdns_item, list->numalloc+GETDNS_LIST_BLOCKSZ))) return GETDNS_RETURN_MEMORY_ERROR; list->items = newlist; list->numalloc += GETDNS_LIST_BLOCKSZ; } list->numinuse++; i = &list->items[index]; if (!*next) { i->dtype = t_int; i->data.n = 55555333; *item = i; return GETDNS_RETURN_GOOD; } if ((next[1] == '0' || next[1] == '-') && (next[2] == '/' || next[2] == '\0')) { i->dtype = t_list; i->data.list = _getdns_list_create_with_mf(&list->mf); return _getdns_list_find_and_add( i->data.list, next, item); } i->dtype = t_dict; i->data.dict = _getdns_dict_create_with_mf(&list->mf); return _getdns_dict_find_and_add(i->data.dict, next, item); } i = &list->items[index]; if (!*next) { switch (i->dtype) { case t_dict : getdns_dict_destroy(i->data.dict); break; case t_list : getdns_list_destroy(i->data.list); break; case t_bindata: _getdns_bindata_destroy( &list->mf, i->data.bindata); break; default : break; } i->dtype = t_int; i->data.n = 33355555; *item = i; return GETDNS_RETURN_GOOD; } else switch (i->dtype) { case t_dict: return _getdns_dict_find_and_add(i->data.dict,next,item); case t_list: return _getdns_list_find_and_add(i->data.list,next,item); default : /* Trying to dereference a non list or dict */ return GETDNS_RETURN_WRONG_TYPE_REQUESTED; } } /*---------------------------------------- getdns_list_get_length */ getdns_return_t getdns_list_get_length(const struct getdns_list * list, size_t * answer) { if (!list || !answer) return GETDNS_RETURN_INVALID_PARAMETER; *answer = list->numinuse; return GETDNS_RETURN_GOOD;; } /* getdns_list_get_length */ /*---------------------------------------- getdns_list_get_data_type */ getdns_return_t getdns_list_get_data_type(const struct getdns_list * list, size_t index, getdns_data_type * answer) { if (!list || !answer) return GETDNS_RETURN_INVALID_PARAMETER; if (index >= list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; *answer = list->items[index].dtype; return GETDNS_RETURN_GOOD; } /* getdns_list_get_data_type */ /*---------------------------------------- getdns_list_get_dict */ getdns_return_t getdns_list_get_dict(const struct getdns_list * list, size_t index, struct getdns_dict ** answer) { if (!list || !answer) return GETDNS_RETURN_INVALID_PARAMETER; if (index >= list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; if (list->items[index].dtype != t_dict) return GETDNS_RETURN_WRONG_TYPE_REQUESTED; *answer = list->items[index].data.dict; return GETDNS_RETURN_GOOD; } /* getdns_list_get_dict */ /*---------------------------------------- getdns_list_get_list */ getdns_return_t getdns_list_get_list(const struct getdns_list * list, size_t index, struct getdns_list ** answer) { if (!list || !answer) return GETDNS_RETURN_INVALID_PARAMETER; if (index >= list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; if (list->items[index].dtype != t_list) return GETDNS_RETURN_WRONG_TYPE_REQUESTED; *answer = list->items[index].data.list; return GETDNS_RETURN_GOOD; } /* getdns_list_get_list */ /*---------------------------------------- getdns_list_get_bindata */ getdns_return_t getdns_list_get_bindata(const struct getdns_list * list, size_t index, struct getdns_bindata ** answer) { if (!list || !answer) return GETDNS_RETURN_INVALID_PARAMETER; if (index >= list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; if (list->items[index].dtype != t_bindata) return GETDNS_RETURN_WRONG_TYPE_REQUESTED; *answer = list->items[index].data.bindata; return GETDNS_RETURN_GOOD; } /* getdns_list_get_bindata */ /*---------------------------------------- getdns_list_get_int */ getdns_return_t getdns_list_get_int(const struct getdns_list * list, size_t index, uint32_t * answer) { if (!list || !answer) return GETDNS_RETURN_INVALID_PARAMETER; if (index >= list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; if (list->items[index].dtype != t_int) return GETDNS_RETURN_WRONG_TYPE_REQUESTED; *answer = list->items[index].data.n; return GETDNS_RETURN_GOOD; } /* getdns_list_get_int */ /*---------------------------------------- _getdns_list_copy */ getdns_return_t _getdns_list_copy(const struct getdns_list * srclist, struct getdns_list ** dstlist) { size_t i; getdns_return_t retval; if (!dstlist) return GETDNS_RETURN_INVALID_PARAMETER; if (!srclist) { *dstlist = NULL; return GETDNS_RETURN_GOOD; } *dstlist = getdns_list_create_with_extended_memory_functions( srclist->mf.mf_arg, srclist->mf.mf.ext.malloc, srclist->mf.mf.ext.realloc, srclist->mf.mf.ext.free ); if (!*dstlist) return GETDNS_RETURN_MEMORY_ERROR; for (i = 0; i < srclist->numinuse; i++) { switch (srclist->items[i].dtype) { case t_int: retval = _getdns_list_append_int(*dstlist, srclist->items[i].data.n); break; case t_list: retval = getdns_list_set_list(*dstlist, (*dstlist)->numinuse, srclist->items[i].data.list); break; case t_bindata: retval = _getdns_list_append_const_bindata(*dstlist, srclist->items[i].data.bindata->size, srclist->items[i].data.bindata->data); break; case t_dict: retval = _getdns_list_append_dict(*dstlist, srclist->items[i].data.dict); break; default: retval = GETDNS_RETURN_WRONG_TYPE_REQUESTED; break; } if (retval != GETDNS_RETURN_GOOD) { getdns_list_destroy(*dstlist); *dstlist = NULL; return retval; } } return GETDNS_RETURN_GOOD; } /* _getdns_list_copy */ struct getdns_list * getdns_list_create_with_extended_memory_functions( void *userarg, void *(*malloc)(void *userarg, size_t), void *(*realloc)(void *userarg, void *, size_t), void (*free)(void *userarg, void *)) { struct getdns_list *list; mf_union mf; if (!malloc || !realloc || !free) return NULL; mf.ext.malloc = malloc; list = userarg == MF_PLAIN ? (struct getdns_list *)(*mf.pln.malloc)( sizeof(struct getdns_list)) : (struct getdns_list *)(*mf.ext.malloc)(userarg, sizeof(struct getdns_list)); if (!list) return NULL; list->mf.mf_arg = userarg; list->mf.mf.ext.malloc = malloc; list->mf.mf.ext.realloc = realloc; list->mf.mf.ext.free = free; list->numinuse = 0; if (!(list->items = GETDNS_XMALLOC( list->mf, getdns_item, GETDNS_LIST_BLOCKSZ))) { GETDNS_FREE(list->mf, list); return NULL; } list->numalloc = GETDNS_LIST_BLOCKSZ; return list; } struct getdns_list * getdns_list_create_with_memory_functions(void *(*malloc)(size_t), void *(*realloc)(void *, size_t), void (*free)(void *)) { mf_union mf; mf.pln.malloc = malloc; mf.pln.realloc = realloc; mf.pln.free = free; return getdns_list_create_with_extended_memory_functions( MF_PLAIN, mf.ext.malloc, mf.ext.realloc, mf.ext.free); } /*-------------------------- getdns_list_create_with_context */ struct getdns_list * getdns_list_create_with_context(const getdns_context *context) { if (context) return getdns_list_create_with_extended_memory_functions( context->mf.mf_arg, context->mf.mf.ext.malloc, context->mf.mf.ext.realloc, context->mf.mf.ext.free ); else return getdns_list_create_with_memory_functions(malloc, realloc, free); } /* getdns_list_create_with_context */ /*---------------------------------------- getdns_list_create */ struct getdns_list * getdns_list_create() { return getdns_list_create_with_context(NULL); } /* getdns_list_create */ static void _getdns_list_destroy_item(struct getdns_list *list, size_t index) { switch (list->items[index].dtype) { case t_dict: getdns_dict_destroy(list->items[index].data.dict); break; case t_list: getdns_list_destroy(list->items[index].data.list); break; case t_bindata: _getdns_bindata_destroy(&list->mf, list->items[index].data.bindata); break; default: break; } } /*---------------------------------------- getdns_list_destroy */ void getdns_list_destroy(struct getdns_list *list) { size_t i; if (!list) return; for (i = 0; i < list->numinuse; i++) _getdns_list_destroy_item(list, i); if (list->items) GETDNS_FREE(list->mf, list->items); GETDNS_FREE(list->mf, list); } /* getdns_list_destroy */ static getdns_return_t _getdns_list_request_index(getdns_list *list, size_t index) { getdns_item *newlist; assert(list); if (index > list->numinuse) return GETDNS_RETURN_NO_SUCH_LIST_ITEM; if (index < list->numinuse) { _getdns_list_destroy_item(list, index); return GETDNS_RETURN_GOOD; } if (list->numalloc > list->numinuse) { list->numinuse++; return GETDNS_RETURN_GOOD; } if (!(newlist = GETDNS_XREALLOC(list->mf, list->items, getdns_item, list->numalloc + GETDNS_LIST_BLOCKSZ))) return GETDNS_RETURN_MEMORY_ERROR; list->numinuse++; list->items = newlist; list->numalloc += GETDNS_LIST_BLOCKSZ; return GETDNS_RETURN_GOOD; } /*---------------------------------------- getdns_list_set_dict */ static getdns_return_t _getdns_list_set_this_dict( getdns_list *list, size_t index, getdns_dict *child_dict) { getdns_return_t r; if (!list || !child_dict) return GETDNS_RETURN_INVALID_PARAMETER; if ((r = _getdns_list_request_index(list, index))) return r; list->items[index].dtype = t_dict; list->items[index].data.dict = child_dict; return GETDNS_RETURN_GOOD; } /* getdns_list_set_dict */ getdns_return_t getdns_list_set_dict( getdns_list *list, size_t index, const getdns_dict *child_dict) { getdns_dict *newdict; getdns_return_t r; if (!list || !child_dict) return GETDNS_RETURN_INVALID_PARAMETER; if ((r = _getdns_dict_copy(child_dict, &newdict))) return r; if ((r = _getdns_list_set_this_dict(list, index, newdict))) getdns_dict_destroy(newdict); return r; } /* getdns_list_set_dict */ /*---------------------------------------- getdns_list_set_list */ getdns_return_t getdns_list_set_list( getdns_list *list, size_t index, const getdns_list *child_list) { getdns_list *newlist; getdns_return_t r; if (!list || !child_list) return GETDNS_RETURN_INVALID_PARAMETER; if ((r = _getdns_list_copy(child_list, &newlist))) return r; if ((r = _getdns_list_request_index(list, index))) { getdns_list_destroy(newlist); return r; } list->items[index].dtype = t_list; list->items[index].data.list = newlist; return GETDNS_RETURN_GOOD; } /* getdns_list_set_list */ /*---------------------------------------- getdns_list_set_bindata */ static getdns_return_t _getdns_list_set_const_bindata( getdns_list *list, size_t index, size_t size, const void *data) { getdns_bindata *newbindata; getdns_return_t r; if (!list) return GETDNS_RETURN_INVALID_PARAMETER; if (!(newbindata = _getdns_bindata_copy(&list->mf, size, data))) return GETDNS_RETURN_MEMORY_ERROR; if ((r = _getdns_list_request_index(list, index))) { _getdns_bindata_destroy(&list->mf, newbindata); return r; } list->items[index].dtype = t_bindata; list->items[index].data.bindata = newbindata; return GETDNS_RETURN_GOOD; } /* getdns_list_set_bindata */ getdns_return_t getdns_list_set_bindata( getdns_list *list, size_t index, const getdns_bindata *child_bindata) { return !child_bindata ? GETDNS_RETURN_INVALID_PARAMETER : _getdns_list_set_const_bindata( list, index, child_bindata->size, child_bindata->data); } /*----------------------------------------- getdns_list_set_string */ static getdns_return_t getdns_list_set_string(getdns_list *list, size_t index, const char *value) { getdns_bindata *newbindata; getdns_return_t r; if (!list || !value) return GETDNS_RETURN_INVALID_PARAMETER; if (!(newbindata = _getdns_bindata_copy( &list->mf, strlen(value) + 1, (uint8_t *)value))) return GETDNS_RETURN_MEMORY_ERROR; newbindata->size -= 1; if ((r = _getdns_list_request_index(list, index))) { _getdns_bindata_destroy(&list->mf, newbindata); return r; } list->items[index].dtype = t_bindata; list->items[index].data.bindata = newbindata; return GETDNS_RETURN_GOOD; } /* getdns_list_set_string */ /*---------------------------------------- getdns_list_set_int */ getdns_return_t getdns_list_set_int(getdns_list * list, size_t index, uint32_t child_int) { getdns_return_t r; if (!list) return GETDNS_RETURN_INVALID_PARAMETER; if ((r = _getdns_list_request_index(list, index))) return r; list->items[index].dtype = t_int; list->items[index].data.n = child_int; return GETDNS_RETURN_GOOD; } /* getdns_list_set_int */ getdns_return_t _getdns_list_append_dict(getdns_list *list, const getdns_dict *child_dict) { if (!list) return GETDNS_RETURN_INVALID_PARAMETER; return getdns_list_set_dict(list, list->numinuse, child_dict); } getdns_return_t _getdns_list_append_this_dict(getdns_list *list, getdns_dict *child_dict) { if (!list) return GETDNS_RETURN_INVALID_PARAMETER; return _getdns_list_set_this_dict(list, list->numinuse, child_dict); } getdns_return_t _getdns_list_append_const_bindata( getdns_list *list, size_t size, const void *data) { if (!list) return GETDNS_RETURN_INVALID_PARAMETER; return _getdns_list_set_const_bindata(list, list->numinuse, size, data); } getdns_return_t _getdns_list_append_string(getdns_list *list, const char *value) { if (!list) return GETDNS_RETURN_INVALID_PARAMETER; return getdns_list_set_string(list, list->numinuse, value); } getdns_return_t _getdns_list_append_int(getdns_list *list, uint32_t child_int) { if (!list) return GETDNS_RETURN_INVALID_PARAMETER; return getdns_list_set_int(list, list->numinuse, child_int); } /* getdns_list.c */ getdns-1.5.1/src/util-internal.c0000644000175000017500000013533713416117763013472 00000000000000/** * * \file util-internal.c * @brief private library routines * * These routines are not intended to be used by applications calling into * the library. * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 #include #include "config.h" #include "getdns/getdns.h" #include "dict.h" #include "list.h" #include "util-internal.h" #include "types-internal.h" #include "rr-dict.h" #if defined(WIRE_DEBUG) && WIRE_DEBUG #include "gldns/wire2str.h" #endif #include "gldns/str2wire.h" #include "gldns/gbuffer.h" #include "gldns/pkthdr.h" #include "dnssec.h" getdns_return_t getdns_dict_util_get_string(const getdns_dict *dict, const char *name, char **result) { struct getdns_bindata *bindata = NULL; if (!result) { return GETDNS_RETURN_GENERIC_ERROR; } *result = NULL; getdns_dict_get_bindata(dict, name, &bindata); if (!bindata) { return GETDNS_RETURN_GENERIC_ERROR; } *result = (char *) bindata->data; return GETDNS_RETURN_GOOD; } getdns_return_t _getdns_dict_to_sockaddr(struct getdns_dict * ns, struct sockaddr_storage * output) { char *address_type = NULL; struct getdns_bindata *address_data = NULL; uint32_t port = 53; memset(output, 0, sizeof(struct sockaddr_storage)); output->ss_family = AF_UNSPEC; uint32_t prt = 0; if (getdns_dict_get_int(ns, GETDNS_STR_PORT, &prt) == GETDNS_RETURN_GOOD) { port = prt; } getdns_dict_util_get_string(ns, GETDNS_STR_ADDRESS_TYPE, &address_type); getdns_dict_get_bindata(ns, GETDNS_STR_ADDRESS_DATA, &address_data); if (!address_type || !address_data) { return GETDNS_RETURN_GENERIC_ERROR; } if (strncmp(GETDNS_STR_IPV4, address_type, strlen(GETDNS_STR_IPV4)) == 0) { /* data is an in_addr_t */ struct sockaddr_in *addr = (struct sockaddr_in *) output; addr->sin_family = AF_INET; addr->sin_port = htons((uint16_t) port); memcpy(&(addr->sin_addr), address_data->data, address_data->size); } else { /* data is a v6 addr in host order */ struct sockaddr_in6 *addr = (struct sockaddr_in6 *) output; addr->sin6_family = AF_INET6; addr->sin6_port = htons((uint16_t) port); memcpy(&(addr->sin6_addr), address_data->data, address_data->size); } return GETDNS_RETURN_GOOD; } getdns_return_t _getdns_sockaddr_to_dict(struct getdns_context *context, struct sockaddr_storage *address, struct getdns_dict ** output) { if (!output || !address) { return GETDNS_RETURN_GENERIC_ERROR; } struct getdns_bindata addr_data; *output = NULL; struct getdns_dict *result = getdns_dict_create_with_context(context); if (address->ss_family == AF_INET) { struct sockaddr_in *addr = (struct sockaddr_in *) address; getdns_dict_util_set_string(result, GETDNS_STR_ADDRESS_TYPE, GETDNS_STR_IPV4); addr_data.size = sizeof(addr->sin_addr); addr_data.data = (uint8_t *) & (addr->sin_addr); getdns_dict_set_bindata(result, GETDNS_STR_ADDRESS_DATA, &addr_data); } else if (address->ss_family == AF_INET6) { struct sockaddr_in6 *addr = (struct sockaddr_in6 *) address; getdns_dict_util_set_string(result, GETDNS_STR_ADDRESS_TYPE, GETDNS_STR_IPV6); addr_data.size = sizeof(addr->sin6_addr); addr_data.data = (uint8_t *) & (addr->sin6_addr); getdns_dict_set_bindata(result, GETDNS_STR_ADDRESS_DATA, &addr_data); } else { // invalid getdns_dict_destroy(result); return GETDNS_RETURN_GENERIC_ERROR; } *output = result; return GETDNS_RETURN_GOOD; } getdns_dict * _getdns_rr_iter2rr_dict_canonical( struct mem_funcs *mf, _getdns_rr_iter *i, uint32_t *orig_ttl) { getdns_dict *rr_dict, *rdata_dict; const uint8_t *bin_data; size_t bin_size, owner_len = 0, rdata_sz; uint32_t int_val = 0; enum wf_data_type { wf_int, wf_bindata, wf_special } val_type; _getdns_rdf_iter rdf_storage, *rdf; getdns_list *repeat_list = NULL; getdns_dict *repeat_dict = NULL; uint8_t ff_bytes[256]; uint16_t rr_type; int canonicalize; gldns_buffer gbuf; getdns_bindata *bindata; uint8_t *data; assert(i); if (!(rr_dict = _getdns_dict_create_with_mf(mf))) return NULL; bin_data = _getdns_owner_if_or_as_decompressed( i, ff_bytes, &bin_size); if (orig_ttl) { if (bin_data != ff_bytes) bin_data = memcpy(ff_bytes, bin_data, bin_size); _dname_canonicalize2(ff_bytes); owner_len = bin_size; } /* question */ if (_getdns_rr_iter_section(i) == SECTION_QUESTION) { if (getdns_dict_set_int(rr_dict, "qtype", (uint32_t) gldns_read_uint16(i->rr_type)) || getdns_dict_set_int(rr_dict, "qclass", (uint32_t) gldns_read_uint16(i->rr_type + 2)) || _getdns_dict_set_const_bindata( rr_dict, "qname", bin_size, bin_data)) { goto error; } return rr_dict; } if (getdns_dict_set_int(rr_dict, "type", (uint32_t)(rr_type = gldns_read_uint16(i->rr_type)))) { goto error; } canonicalize = orig_ttl && _dnssec_rdata_to_canonicalize(rr_type) && (i->rr_type + 12 <= i->nxt) /* To estimate rdata size */; if (rr_type == GETDNS_RRTYPE_OPT) { int_val = gldns_read_uint16(i->rr_type + 6); if (getdns_dict_set_int(rr_dict, "udp_payload_size", (uint32_t) gldns_read_uint16(i->rr_type + 2)) || getdns_dict_set_int(rr_dict, "extended_rcode", (uint32_t) *(i->rr_type + 4)) || getdns_dict_set_int(rr_dict, "version", (uint32_t) *(i->rr_type + 5)) || getdns_dict_set_int(rr_dict, "do", (uint32_t) ((int_val & 0x8000) >> 15)) || getdns_dict_set_int(rr_dict, "z", (uint32_t) (int_val & 0x7FF))) { goto error; } } else if (getdns_dict_set_int(rr_dict, "class", (uint32_t) gldns_read_uint16(i->rr_type + 2)) || getdns_dict_set_int(rr_dict, "ttl", ( orig_ttl && rr_type != GETDNS_RRTYPE_RRSIG ? *orig_ttl : (uint32_t) gldns_read_uint32(i->rr_type + 4))) || _getdns_dict_set_const_bindata( rr_dict, "name", bin_size, bin_data)) { goto error; } if (!(rdata_dict = _getdns_dict_create_with_mf(mf))) return NULL; if (i->rr_type + 10 <= i->nxt && !canonicalize) { bin_size = i->nxt - (i->rr_type + 10); bin_data = i->rr_type + 10; if (_getdns_dict_set_const_bindata( rdata_dict, "rdata_raw", bin_size, bin_data)) goto rdata_error; } if (canonicalize) rdata_sz = 0; for ( rdf = _getdns_rdf_iter_init(&rdf_storage, i) ; rdf; rdf = _getdns_rdf_iter_next(rdf)) { if (canonicalize && !(rdf->rdd_pos->type & GETDNS_RDF_DNAME)) { rdata_sz += rdf->nxt - rdf->pos; } if (rdf->rdd_pos->type & GETDNS_RDF_INTEGER) { val_type = wf_int; switch (rdf->rdd_pos->type & GETDNS_RDF_FIXEDSZ) { case 1: int_val = *rdf->pos; break; case 2: int_val = gldns_read_uint16(rdf->pos); break; case 4: int_val = gldns_read_uint32(rdf->pos); break; default: goto rdata_error; } } else if (rdf->rdd_pos->type & GETDNS_RDF_DNAME) { val_type = wf_bindata; bin_data = _getdns_rdf_if_or_as_decompressed( rdf, ff_bytes, &bin_size); if (canonicalize) { if (bin_data != ff_bytes) bin_data = memcpy(ff_bytes, bin_data, bin_size); _dname_canonicalize2(ff_bytes); rdata_sz += bin_size; } } else if (rdf->rdd_pos->type & GETDNS_RDF_BINDATA) { val_type = wf_bindata; if (rdf->rdd_pos->type & GETDNS_RDF_FIXEDSZ) { bin_size = rdf->rdd_pos->type & GETDNS_RDF_FIXEDSZ; bin_data = rdf->pos; } else switch(rdf->rdd_pos->type & GETDNS_RDF_LEN_VAL){ case 0x100: bin_size = *rdf->pos; bin_data = rdf->pos + 1; break; case 0x200: bin_size = gldns_read_uint16(rdf->pos); bin_data = rdf->pos + 2; break; default: bin_size = rdf->nxt - rdf->pos; bin_data = rdf->pos; break; } } else if (rdf->rdd_pos->type == GETDNS_RDF_SPECIAL) val_type = wf_special; else assert(((val_type = wf_int), 0)); if (! rdf->rdd_repeat) { switch (val_type) { case wf_int: if (getdns_dict_set_int(rdata_dict, rdf->rdd_pos->name, int_val)) goto rdata_error; break; case wf_bindata: if (_getdns_dict_set_const_bindata(rdata_dict, rdf->rdd_pos->name, bin_size, bin_data)) goto rdata_error; break; case wf_special: if (rdf->rdd_pos->special->wire2dict( rdata_dict, rdf->pos)) goto rdata_error; default: break; } continue; } if (rdf->rdd_pos == rdf->rdd_repeat) { /* list with rdf values */ if (! repeat_list && !(repeat_list = _getdns_list_create_with_mf(mf))) goto rdata_error; switch (val_type) { case wf_int: if (_getdns_list_append_int(repeat_list, int_val)) goto rdata_error; break; case wf_bindata: if (_getdns_list_append_const_bindata( repeat_list, bin_size, bin_data)) goto rdata_error; break; /* Repetitive special types do not exist (yet) * * LCOV_EXCL_START */ case wf_special: /* Repetitive special types * must have this function */ assert(rdf->rdd_pos->special->wire2list); if (rdf->rdd_pos->special->wire2list( repeat_list, rdf->pos)) goto rdata_error; /* LCOV_EXCL_STOP */ default: break; } continue; } if (rdf->rdd_pos == rdf->rdd_repeat + 1) { if (repeat_dict) { if (! repeat_list && !(repeat_list = _getdns_list_create_with_mf(mf))) goto rdata_error; if (_getdns_list_append_this_dict( repeat_list, repeat_dict)) goto rdata_error; repeat_dict = NULL; } if (!(repeat_dict = _getdns_dict_create_with_mf(mf))) goto rdata_error; } assert(repeat_dict); switch (val_type) { case wf_int: if (getdns_dict_set_int(repeat_dict, rdf->rdd_pos->name, int_val)) goto rdata_error; break; case wf_bindata: if (_getdns_dict_set_const_bindata(repeat_dict, rdf->rdd_pos->name, bin_size, bin_data)) goto rdata_error; break; case wf_special: if (rdf->rdd_pos->special->wire2dict( repeat_dict, rdf->pos)) goto rdata_error; default: break; } } if (repeat_dict) { if (!repeat_list && !(repeat_list = _getdns_list_create_with_mf(mf))) goto rdata_error; if (_getdns_list_append_this_dict(repeat_list, repeat_dict)) goto rdata_error; repeat_dict = NULL; } if (repeat_list) { if (_getdns_dict_set_this_list(rdata_dict, rdf_storage.rdd_repeat->name, repeat_list)) goto rdata_error; repeat_list = NULL; } if (_getdns_dict_set_this_dict(rr_dict, "rdata", rdata_dict)) goto rdata_error; if (canonicalize && rdata_sz) { if (!(data = GETDNS_XMALLOC( *mf, uint8_t, owner_len + 10 + rdata_sz))) return rr_dict; gldns_buffer_init_frm_data(&gbuf, data, owner_len+10+rdata_sz); if (_getdns_rr_dict2wire(rr_dict, &gbuf) || gldns_buffer_position(&gbuf) != owner_len + 10 + rdata_sz || !(bindata = GETDNS_MALLOC(*mf, struct getdns_bindata))) { GETDNS_FREE(*mf, data); return rr_dict; } bindata->size = rdata_sz; bindata->data = memmove(data, data + owner_len + 10, rdata_sz); (void) _getdns_dict_set_this_bindata(rr_dict, "/rdata/rdata_raw", bindata); } return rr_dict; rdata_error: getdns_list_destroy(repeat_list); getdns_dict_destroy(repeat_dict); getdns_dict_destroy(rdata_dict); error: getdns_dict_destroy(rr_dict); return NULL; } getdns_dict * _getdns_rr_iter2rr_dict(struct mem_funcs *mf, _getdns_rr_iter *i) { return _getdns_rr_iter2rr_dict_canonical(mf, i, NULL); } static inline getdns_dict * set_dict(getdns_dict **var, getdns_dict *value) { if (*var) getdns_dict_destroy(*var); return *var = value; } static inline int has_all_numeric_label(const uint8_t *dname) { size_t i; while (*dname && !(*dname & 0xc0)) { for (i = 1; i <= *dname; i++) { if (!isdigit(dname[i])) break; } if (i > *dname) return 1; dname += *dname + 1; } return 0; } typedef struct _srv_rr { _getdns_rr_iter i; unsigned running_sum; } _srv_rr; typedef struct _srvs { size_t capacity; size_t count; _srv_rr *rrs; } _srvs; static int _grow_srvs(struct mem_funcs *mf, _srvs *srvs) { _srv_rr *new_rrs; if (!(new_rrs = GETDNS_XREALLOC( *mf, srvs->rrs, _srv_rr, srvs->capacity * 2))) return 0; /* Memory error */ srvs->capacity *= 2; srvs->rrs = new_rrs; return 1; /* Success */ } #define SET_WIRE_INT(X,Y) if (getdns_dict_set_int(header, #X , (int) \ GLDNS_ ## Y ## _WIRE(req->response))) goto error #define SET_WIRE_BIT(X,Y) if (getdns_dict_set_int(header, #X , \ GLDNS_ ## Y ## _WIRE(req->response) ? 1 : 0)) goto error #define SET_WIRE_CNT(X,Y) if (getdns_dict_set_int(header, #X , (int) \ GLDNS_ ## Y (req->response))) goto error static getdns_dict * _getdns_create_reply_dict(getdns_context *context, getdns_network_req *req, getdns_list *just_addrs, int *rrsigs_in_answer, _srvs *srvs) { /* turn a packet into this glorious structure * * { # This is the first reply * "header": { "id": 23456, "qr": 1, "opcode": 0, ... }, * "question": { "qname": , "qtype": 1, "qclass": 1 }, * "answer": * [ * { * "name": , * "type": 1, * "class": 1, * "ttl": 33000, * "rdata": * { * "ipv4_address": * "rdata_raw": * } * } * ], * "authority": * [ * { * "name": , * "type": 1, * "class": 1, * "ttl": 600, * "rdata": * { * "ipv4_address": * "rdata_raw": * } * } * ] * "additional": [], * "canonical_name": , * "answer_type": GETDNS_NAMETYPE_DNS * } * */ getdns_return_t r = GETDNS_RETURN_GOOD; getdns_dict *result = getdns_dict_create_with_context(context); getdns_dict *question = NULL; getdns_list *sections[16] = { NULL, NULL , getdns_list_create_with_context(context) , NULL , getdns_list_create_with_context(context) , NULL, NULL, NULL , getdns_list_create_with_context(context) , NULL, NULL, NULL, NULL, NULL, NULL, NULL }; getdns_dict *rr_dict = NULL; _getdns_rr_iter rr_iter_storage, *rr_iter; _getdns_rdf_iter rdf_iter_storage, *rdf_iter; size_t bin_size; const uint8_t *bin_data; _getdns_section section; uint8_t owner_name_space[256], query_name_space[256]; const uint8_t *owner_name, *query_name; size_t owner_name_len = sizeof(owner_name_space), query_name_len = sizeof(query_name_space); int all_numeric_label; uint16_t rr_type; getdns_dict *header = NULL; getdns_list *bad_dns = NULL; _getdns_rrset_spc answer_spc; _getdns_rrset *answer; if (!result) goto error; if (!(header = getdns_dict_create_with_context(context))) goto error; SET_WIRE_INT(id, ID); SET_WIRE_BIT(qr, QR); SET_WIRE_BIT(aa, AA); SET_WIRE_BIT(tc, TC); SET_WIRE_BIT(rd, RD); SET_WIRE_BIT(cd, CD); SET_WIRE_BIT(ra, RA); SET_WIRE_BIT(ad, AD); SET_WIRE_INT(opcode, OPCODE); SET_WIRE_INT(rcode, RCODE); SET_WIRE_BIT(z, Z); SET_WIRE_CNT(qdcount, QDCOUNT); SET_WIRE_CNT(ancount, ANCOUNT); SET_WIRE_CNT(nscount, NSCOUNT); SET_WIRE_CNT(arcount, ARCOUNT); /* header */ if ((r = _getdns_dict_set_this_dict(result, "header", header))) goto error; header = NULL; if (req->query && (rr_iter = _getdns_rr_iter_init(&rr_iter_storage, req->query , req->response - req->query))) query_name = _getdns_owner_if_or_as_decompressed( rr_iter, query_name_space, &query_name_len); else query_name = NULL; for ( rr_iter = _getdns_rr_iter_init(&rr_iter_storage , req->response , req->response_len) ; rr_iter ; rr_iter = _getdns_rr_iter_next(rr_iter)) { if (!set_dict(&rr_dict, _getdns_rr_iter2rr_dict(&context->mf, rr_iter))) continue; section = _getdns_rr_iter_section(rr_iter); if (section == SECTION_QUESTION) { if (!query_name) query_name = _getdns_owner_if_or_as_decompressed( rr_iter, query_name_space, &query_name_len); if (_getdns_dict_set_this_dict(result, "question", rr_dict)) goto error; else rr_dict = NULL; continue; } rr_type = gldns_read_uint16(rr_iter->rr_type); if (section > SECTION_QUESTION && rr_type == GETDNS_RRTYPE_RRSIG && rrsigs_in_answer) *rrsigs_in_answer = 1; if (section != SECTION_ANSWER) { if (_getdns_list_append_this_dict( sections[section], rr_dict)) goto error; else rr_dict = NULL; continue; } if (req->follow_redirects == GETDNS_REDIRECTS_DO_NOT_FOLLOW) { owner_name_len = sizeof(owner_name_space); owner_name = _getdns_owner_if_or_as_decompressed( rr_iter, owner_name_space, &owner_name_len); if (!_getdns_dname_equal(query_name, owner_name)) continue; } if (_getdns_list_append_this_dict( sections[SECTION_ANSWER], rr_dict)) goto error; else rr_dict = NULL; if (srvs->capacity && rr_type == GETDNS_RRTYPE_SRV) { if (srvs->count >= srvs->capacity && !_grow_srvs(&context->mf, srvs)) goto error; srvs->rrs[srvs->count++].i = *rr_iter; continue; } if (rr_type != GETDNS_RRTYPE_A && rr_type != GETDNS_RRTYPE_AAAA) continue; if (!just_addrs) continue; if (!(rdf_iter = _getdns_rdf_iter_init( &rdf_iter_storage, rr_iter))) continue; bin_size = rdf_iter->nxt - rdf_iter->pos; bin_data = rdf_iter->pos; if (!set_dict(&rr_dict, getdns_dict_create_with_context(context)) || getdns_dict_util_set_string(rr_dict, "address_type", rr_type == GETDNS_RRTYPE_A ? "IPv4" : "IPv6" ) || _getdns_dict_set_const_bindata( rr_dict, "address_data", bin_size, bin_data) || _getdns_list_append_this_dict(just_addrs, rr_dict)) { goto error; } rr_dict = NULL; } if (!_getdns_dict_set_this_list(result, "answer", sections[SECTION_ANSWER])) sections[SECTION_ANSWER] = NULL; else goto error; if (!_getdns_dict_set_this_list(result, "authority", sections[SECTION_AUTHORITY])) sections[SECTION_AUTHORITY] = NULL; else goto error; if (!_getdns_dict_set_this_list(result, "additional", sections[SECTION_ADDITIONAL])) sections[SECTION_ADDITIONAL] = NULL; else goto error; /* other stuff * Note that spec doesn't explicitly mention these. * They are only showcased in the response dict example */ if (getdns_dict_set_int(result, "answer_type", GETDNS_NAMETYPE_DNS)) goto error; answer = _getdns_rrset_answer(&answer_spc, req->response , req->response_len); if (answer_spc.rrset.name && _getdns_dict_set_const_bindata(result, "canonical_name" , answer_spc.name_len , answer_spc.rrset.name)) goto error; if (!req->owner->add_warning_for_bad_dns) goto success; if (!(bad_dns = getdns_list_create_with_context(context))) goto error; if ( !answer && req->request_type != GETDNS_RRTYPE_CNAME && query_name && answer_spc.rrset.name && !_getdns_dname_equal(query_name, answer_spc.rrset.name) && _getdns_list_append_int(bad_dns , GETDNS_BAD_DNS_CNAME_RETURNED_FOR_OTHER_TYPE)) goto error; all_numeric_label = 0; for ( rr_iter = _getdns_rr_iter_init(&rr_iter_storage , req->response , req->response_len) ; rr_iter && !all_numeric_label ; rr_iter = _getdns_rr_iter_next(rr_iter)) { owner_name = _getdns_owner_if_or_as_decompressed( rr_iter, owner_name_space, &owner_name_len); if (has_all_numeric_label(owner_name)) { all_numeric_label = 1; break; } if (_getdns_rr_iter_section(rr_iter) == SECTION_QUESTION) continue; for ( rdf_iter = _getdns_rdf_iter_init(&rdf_iter_storage, rr_iter) ; rdf_iter; rdf_iter = _getdns_rdf_iter_next(rdf_iter)) { if (!(rdf_iter->rdd_pos->type & GETDNS_RDF_DNAME)) continue; owner_name = _getdns_rdf_if_or_as_decompressed( rdf_iter, owner_name_space, &owner_name_len); if (has_all_numeric_label(owner_name)) { all_numeric_label = 1; break; } } } if (all_numeric_label && _getdns_list_append_int(bad_dns, GETDNS_BAD_DNS_ALL_NUMERIC_LABEL)) goto error; if (_getdns_dict_set_this_list(result, "bad_dns", bad_dns)) goto error; else bad_dns = NULL; goto success; error: getdns_dict_destroy(result); result = NULL; success: getdns_dict_destroy(header); getdns_dict_destroy(rr_dict); getdns_list_destroy(sections[SECTION_ADDITIONAL]); getdns_list_destroy(sections[SECTION_AUTHORITY]); getdns_list_destroy(sections[SECTION_ANSWER]); getdns_dict_destroy(question); getdns_list_destroy(bad_dns); return result; } static getdns_dict * _getdns_create_call_reporting_dict( getdns_context *context, getdns_network_req *netreq) { getdns_bindata qname; getdns_dict *netreq_debug; getdns_dict *address_debug = NULL; assert(netreq); /* It is the responsibility of the caller to free this */ if (!(netreq_debug = getdns_dict_create_with_context(context))) return NULL; qname.data = netreq->owner->name; qname.size = netreq->owner->name_len; if (getdns_dict_set_bindata(netreq_debug, "query_name", &qname) || getdns_dict_set_int( netreq_debug, "query_type" , netreq->request_type ) || /* Safe, because uint32_t facilitates RRT's of almost 50 days*/ getdns_dict_set_int(netreq_debug, "run_time/ms", (uint32_t)(( netreq->debug_end_time - netreq->debug_start_time)/1000))) { getdns_dict_destroy(netreq_debug); return NULL; } else if (!netreq->upstream) { if (getdns_dict_set_int( netreq_debug, "resolution_type", GETDNS_RESOLUTION_RECURSING)) { getdns_dict_destroy(netreq_debug); return NULL; } /* Nothing more for full recursion */ return netreq_debug; } if (getdns_dict_set_int( netreq_debug, "resolution_type", GETDNS_RESOLUTION_STUB)) { getdns_dict_destroy(netreq_debug); return NULL; } /* Stub resolver debug data */ _getdns_sockaddr_to_dict( context, &netreq->upstream->addr, &address_debug); if (_getdns_dict_set_this_dict(netreq_debug,"query_to",address_debug)){ getdns_dict_destroy(address_debug); return NULL; } getdns_transport_list_t transport = netreq->upstream->transport; /* Same upstream is used for UDP and TCP, so netreq keeps track of what was actually used for the last successful query.*/ if (transport == GETDNS_TRANSPORT_TCP && netreq->debug_udp == 1) { transport = GETDNS_TRANSPORT_UDP; if (getdns_dict_set_int( netreq_debug, "udp_responses_for_this_upstream", netreq->upstream->udp_responses)) { getdns_dict_destroy(netreq_debug); return NULL; } if (getdns_dict_set_int( netreq_debug, "udp_timeouts_for_this_upstream", netreq->upstream->udp_timeouts)) { getdns_dict_destroy(netreq_debug); return NULL; } } if (getdns_dict_set_int( netreq_debug, "transport", transport)) { getdns_dict_destroy(netreq_debug); return NULL; } if (transport != GETDNS_TRANSPORT_UDP) { /* Report the idle timeout actually used on the connection. Must trim, maximum used in practice is 6553500ms, but this is stored in a uint64_t.*/ if (netreq->upstream->keepalive_timeout > UINT32_MAX) { if (getdns_dict_set_int( netreq_debug, "idle timeout in ms (overflow)", UINT32_MAX)) { getdns_dict_destroy(netreq_debug); return NULL; } } else{ uint32_t idle_timeout = (uint32_t) netreq->upstream->keepalive_timeout; if (getdns_dict_set_int( netreq_debug, "idle timeout in ms", idle_timeout)) { getdns_dict_destroy(netreq_debug); return NULL; } } if (getdns_dict_set_int( netreq_debug, "server_keepalive_received", netreq->upstream->server_keepalive_received)) { getdns_dict_destroy(netreq_debug); return NULL; } /* The running totals are only updated when a connection is closed. Since it is open as we have just used it, calcualte the value on the fly */ if (getdns_dict_set_int( netreq_debug, "responses_on_this_connection", netreq->upstream->responses_received)) { getdns_dict_destroy(netreq_debug); return NULL; } if (getdns_dict_set_int( netreq_debug, "timeouts_on_this_connection", netreq->upstream->responses_timeouts)) { getdns_dict_destroy(netreq_debug); return NULL; } if (getdns_dict_set_int( netreq_debug, "responses_for_this_upstream", netreq->upstream->responses_received + netreq->upstream->total_responses)) { getdns_dict_destroy(netreq_debug); return NULL; } if (getdns_dict_set_int( netreq_debug, "timeouts_for_this_upstream", netreq->upstream->responses_timeouts + netreq->upstream->total_timeouts)) { getdns_dict_destroy(netreq_debug); return NULL; } } if (netreq->upstream->transport != GETDNS_TRANSPORT_TLS) return netreq_debug; /* Only include the auth status if TLS was used */ if (getdns_dict_util_set_string(netreq_debug, "tls_auth_status", _getdns_auth_str(netreq->debug_tls_auth_status))){ getdns_dict_destroy(netreq_debug); return NULL; } if (getdns_dict_util_set_string(netreq_debug, "tls_version", netreq->debug_tls_version)){ getdns_dict_destroy(netreq_debug); return NULL; } if (getdns_dict_set_bindata(netreq_debug, "tls_peer_cert", &netreq->debug_tls_peer_cert)) { getdns_dict_destroy(netreq_debug); return NULL; } netreq->debug_tls_peer_cert.size = 0; OPENSSL_free(netreq->debug_tls_peer_cert.data); netreq->debug_tls_peer_cert.data = NULL; return netreq_debug; } static inline int _srv_prio(_getdns_rr_iter *x) { return x->nxt < x->rr_type+12 ? 65536 : (int)gldns_read_uint16(x->rr_type+10); } static inline int _srv_weight(_getdns_rr_iter *x) { return x->nxt < x->rr_type+14 ? 0 : (int)gldns_read_uint16(x->rr_type+12); } static int _srv_cmp(const void *a, const void *b) { return _srv_prio((_getdns_rr_iter *)a) - _srv_prio((_getdns_rr_iter *)b); } static void _rfc2782_sort(_srv_rr *start, _srv_rr *end) { uint32_t running_sum, n; _srv_rr *i, *j, swap; /* First move all SRVs with weight 0 to the beginning of the list */ for (i = start; i < end && _srv_weight(&i->i) == 0; i++) ; /* pass */ for (j = i + 1; j < end; j++) { if (_srv_weight(&j->i) == 0) { swap = *i; *i = *j; *j = swap; i++; } } /* Now all SRVs are at the beginning, calculate running_sum */ running_sum = 0; for (i = start; i < end; i++) { running_sum += _srv_weight(&i->i); i->running_sum = running_sum; } n = arc4random_uniform(running_sum); for (i = start; i < end; i++) { if (i->running_sum >= n) break; } if (i > start && i < end) { swap = *start; *start = *i; *i = swap; _rfc2782_sort(start + 1, end); } } static getdns_list * _create_srv_addrs(getdns_context *context, _srvs *srvs) { getdns_list *srv_addrs; size_t i, j; qsort(srvs->rrs, srvs->count, sizeof(_srv_rr), _srv_cmp); /* The SRVs are now sorted by priority (lowest first). Now determine * server selection order for the SRVs with the same priority with * the algorithm described in RFC2782: * * To select a target to be contacted next, arrange all SRV RRs * (that have not been ordered yet) in any order, except that all * those with weight 0 are placed at the beginning of the list. * * Compute the sum of the weights of those RRs, and with each RR * associate the running sum in the selected order. Then choose a * uniform random number between 0 and the sum computed * (inclusive), and select the RR whose running sum value is the * first in the selected order which is greater than or equal to * the random number selected. The target host specified in the * selected SRV RR is the next one to be contacted by the client. * Remove this SRV RR from the set of the unordered SRV RRs and * apply the described algorithm to the unordered SRV RRs to select * the next target host. Continue the ordering process until there * are no unordered SRV RRs. This process is repeated for each * Priority. */ for (i = 0; i < srvs->count; i = j) { /* Determine range of SRVs with same priority */ for ( j = i + 1 ; j < srvs->count && _srv_prio(&srvs->rrs[i].i) == _srv_prio(&srvs->rrs[j].i) ; j++) ; /* pass */ if (j == i + 1) continue; /* SRVs with same prio range from i till j (exclusive). */ _rfc2782_sort(srvs->rrs + i, srvs->rrs + j); } if (!(srv_addrs = getdns_list_create_with_context(context))) return NULL; for (i = 0; i < srvs->count; i++) { _getdns_rr_iter *rr = &srvs->rrs[i].i; getdns_dict *d; _getdns_rdf_iter rdf_storage, *rdf; const uint8_t *dname; uint8_t dname_spc[256]; size_t dname_sz = sizeof(dname_spc); _getdns_rrset a; _getdns_rrtype_iter a_rr_spc, *a_rr; int addresses_found = 0; if ( !(d = getdns_dict_create_with_context(context)) || !(rdf = _getdns_rdf_iter_init_at(&rdf_storage, rr, 2)) || !(rdf->rdd_pos->type & GETDNS_RDF_INTEGER) || (rdf->rdd_pos->type & GETDNS_RDF_FIXEDSZ) != 2 || getdns_dict_set_int(d, "port", (uint32_t) gldns_read_uint16(rdf->pos)) || !(rdf = _getdns_rdf_iter_init_at(&rdf_storage, rr, 3)) || !(rdf->rdd_pos->type & GETDNS_RDF_DNAME) || !(dname = _getdns_rdf_if_or_as_decompressed( rdf, dname_spc, &dname_sz)) || _getdns_dict_set_const_bindata( d, "domain_name", dname_sz, dname)) { /* error */ getdns_dict_destroy(d); continue; } a.name = dname; a.rr_class = rr_iter_class(rr); a.rr_type = GETDNS_RRTYPE_AAAA; a.pkt = rr->pkt; a.pkt_len = rr->pkt_end - rr->pkt; a.sections = SECTION_ADDITIONAL; for ( a_rr = _getdns_rrtype_iter_init(&a_rr_spc, &a) ; a_rr ; a_rr = _getdns_rrtype_iter_next(a_rr)) { if ( a_rr->rr_i.nxt - (a_rr->rr_i.rr_type + 10) == 16 && !getdns_dict_util_set_string( d, "address_type", "IPv6") && !_getdns_dict_set_const_bindata( d, "address_data", 16, a_rr->rr_i.rr_type + 10) && !_getdns_list_append_dict(srv_addrs, d)) addresses_found++; } a.rr_type = GETDNS_RRTYPE_A; for ( a_rr = _getdns_rrtype_iter_init(&a_rr_spc, &a) ; a_rr ; a_rr = _getdns_rrtype_iter_next(a_rr)) { if ( a_rr->rr_i.nxt - (a_rr->rr_i.rr_type + 10) ==4 && !getdns_dict_util_set_string( d, "address_type", "IPv4") && !_getdns_dict_set_const_bindata( d, "address_data", 4, a_rr->rr_i.rr_type + 10) && !_getdns_list_append_dict(srv_addrs, d)) addresses_found++; } if ( addresses_found || _getdns_list_append_this_dict(srv_addrs, d)) getdns_dict_destroy(d); } return srv_addrs; } getdns_dict * _getdns_create_getdns_response(getdns_dns_req *completed_request) { getdns_dict *result; getdns_list *just_addrs = NULL; getdns_list *srv_addrs = NULL; getdns_list *replies_full; getdns_list *replies_tree; getdns_list *call_reporting = NULL; getdns_network_req *netreq, **netreq_p; int rrsigs_in_answer = 0; getdns_dict *reply; getdns_bindata *canonical_name = NULL; int nreplies = 0, nanswers = 0; int nsecure = 0, ninsecure = 0, nindeterminate = 0, nbogus = 0; getdns_dict *netreq_debug; _srvs srvs = { 0, 0, NULL }; _getdns_rrset_spc answer_spc; /* info (bools) about dns_req */ int dnssec_return_status; getdns_context *context; assert(completed_request); context = completed_request->context; if (!(result = getdns_dict_create_with_context(context))) return NULL; dnssec_return_status = completed_request->dnssec || completed_request->dnssec_return_status || completed_request->dnssec_return_only_secure || completed_request->dnssec_return_all_statuses #ifdef DNSSEC_ROADBLOCK_AVOIDANCE || completed_request->dnssec_roadblock_avoidance #endif ; if (completed_request->netreqs[0]->request_type == GETDNS_RRTYPE_A || completed_request->netreqs[0]->request_type == GETDNS_RRTYPE_AAAA) just_addrs = getdns_list_create_with_context( completed_request->context); else if ( completed_request->netreqs[0]->request_type == GETDNS_RRTYPE_SRV) { srvs.capacity = 100; if (!(srvs.rrs = GETDNS_XMALLOC( context->mf, _srv_rr, srvs.capacity))) { srvs.capacity = 0; goto error_free_result; } } if (getdns_dict_set_int(result, GETDNS_STR_KEY_ANSWER_TYPE, GETDNS_NAMETYPE_DNS)) goto error_free_result; if (!(replies_full = getdns_list_create_with_context(context))) goto error_free_result; if (!(replies_tree = getdns_list_create_with_context(context))) goto error_free_replies_full; if (completed_request->return_call_reporting && !(call_reporting = getdns_list_create_with_context(context))) goto error_free_replies_full; for ( netreq_p = completed_request->netreqs ; (netreq = *netreq_p) ; netreq_p++) { if (call_reporting && ( netreq->response_len || netreq->state == NET_REQ_TIMED_OUT)) { if (!(netreq_debug = _getdns_create_call_reporting_dict(context,netreq))) goto error; if (_getdns_list_append_this_dict( call_reporting, netreq_debug)) goto error; netreq_debug = NULL; } if (! netreq->response_len) continue; if (netreq->tsig_status == GETDNS_DNSSEC_INSECURE) _getdns_network_validate_tsig(netreq); nreplies++; switch (netreq->dnssec_status) { case GETDNS_DNSSEC_SECURE : nsecure++; break; case GETDNS_DNSSEC_INSECURE : ninsecure++; break; case GETDNS_DNSSEC_INDETERMINATE: nindeterminate++; ninsecure++; break; case GETDNS_DNSSEC_BOGUS : if (dnssec_return_status) nbogus++; break; } if (! completed_request->dnssec_return_all_statuses && ! completed_request->dnssec_return_validation_chain) { if (dnssec_return_status && netreq->dnssec_status == GETDNS_DNSSEC_BOGUS) continue; else if (completed_request->dnssec_return_only_secure && netreq->dnssec_status != GETDNS_DNSSEC_SECURE) continue; else if (completed_request->dnssec && netreq->dnssec_status == GETDNS_DNSSEC_INDETERMINATE) continue; else if (netreq->tsig_status == GETDNS_DNSSEC_BOGUS) continue; } if (!(reply = _getdns_create_reply_dict(context, netreq, just_addrs, &rrsigs_in_answer, &srvs))) goto error; if (!canonical_name) { if (!getdns_dict_get_bindata( reply, "canonical_name", &canonical_name) && getdns_dict_set_bindata( result, "canonical_name", canonical_name)) goto error; } /* TODO: Check instead if canonical_name for request_type * is in the answer section. */ if (_getdns_rrset_answer(&answer_spc, netreq->response , netreq->response_len)) nanswers++; if (dnssec_return_status || completed_request->dnssec_return_validation_chain) { if (getdns_dict_set_int(reply, "dnssec_status", netreq->dnssec_status)) goto error; } if (netreq->tsig_status != GETDNS_DNSSEC_INDETERMINATE) { if (getdns_dict_set_int(reply, "tsig_status", netreq->tsig_status)) goto error; } if (_getdns_list_append_this_dict(replies_tree, reply)) { getdns_dict_destroy(reply); goto error; } if (_getdns_list_append_const_bindata(replies_full, netreq->response_len, netreq->response)) goto error; } if (_getdns_dict_set_this_list(result, "replies_tree", replies_tree)) goto error; replies_tree = NULL; if (!canonical_name && _getdns_dict_set_const_bindata(result, "canonical_name", completed_request->name_len, completed_request->name)) goto error; if (call_reporting) { if (_getdns_dict_set_this_list( result, "call_reporting", call_reporting)) goto error_free_call_reporting; call_reporting = NULL; } if (_getdns_dict_set_this_list(result, "replies_full", replies_full)) goto error_free_replies_full; replies_full = NULL; if (just_addrs) { if (_getdns_dict_set_this_list( result, GETDNS_STR_KEY_JUST_ADDRS, just_addrs)) goto error_free_result; just_addrs = NULL; } if (srvs.capacity) { if (!(srv_addrs = _create_srv_addrs(context, &srvs)) || _getdns_dict_set_this_list( result, "srv_addresses", srv_addrs)) goto error_free_result; GETDNS_FREE(context->mf, srvs.rrs); } if (getdns_dict_set_int(result, GETDNS_STR_KEY_STATUS, completed_request->request_timed_out || nreplies == 0 ? GETDNS_RESPSTATUS_ALL_TIMEOUT : ( completed_request->dnssec && nsecure == 0 && nindeterminate ) > 0 ? GETDNS_RESPSTATUS_NO_SECURE_ANSWERS : ( completed_request->dnssec_return_only_secure && nsecure == 0 && ninsecure ) > 0 ? GETDNS_RESPSTATUS_NO_SECURE_ANSWERS : ( completed_request->dnssec_return_only_secure || completed_request->dnssec ) && nsecure == 0 && nbogus > 0 ? GETDNS_RESPSTATUS_ALL_BOGUS_ANSWERS : nanswers == 0 ? GETDNS_RESPSTATUS_NO_NAME : GETDNS_RESPSTATUS_GOOD)) goto error_free_result; return result; error: /* cleanup */ getdns_list_destroy(replies_tree); error_free_call_reporting: getdns_list_destroy(call_reporting); error_free_replies_full: getdns_list_destroy(replies_full); error_free_result: if (srvs.capacity) GETDNS_FREE(context->mf, srvs.rrs); getdns_list_destroy(srv_addrs); getdns_list_destroy(just_addrs); getdns_dict_destroy(result); return NULL; } #ifdef HAVE_LIBUNBOUND getdns_return_t getdns_apply_network_result(getdns_network_req* netreq, int rcode, void *pkt, int pkt_len, int sec, char* why_bogus) { (void)why_bogus; netreq->dnssec_status = sec == 0 ? GETDNS_DNSSEC_INSECURE : sec == 2 ? GETDNS_DNSSEC_SECURE : GETDNS_DNSSEC_BOGUS; if (pkt) { if (netreq->max_udp_payload_size < pkt_len) netreq->response = GETDNS_XMALLOC( netreq->owner->context->mf, uint8_t, pkt_len ); (void) memcpy(netreq->response, pkt, (netreq->response_len = pkt_len)); return GETDNS_RETURN_GOOD; } if (rcode == GETDNS_RCODE_SERVFAIL) { /* Likely to be caused by timeout from a synchronous * lookup. Don't forge a packet. */ return GETDNS_RETURN_GOOD; } /* Likely to be because libunbound refused the request * so ub_res->answer_packet=NULL, ub_res->answer_len=0 * So we need to create an answer packet. */ gldns_write_uint16(netreq->response , 0); /* query_id */ gldns_write_uint16(netreq->response + 2, 0); /* reset all flags */ gldns_write_uint16(netreq->response + GLDNS_QDCOUNT_OFF, 1); gldns_write_uint16(netreq->response + GLDNS_ANCOUNT_OFF, 0); gldns_write_uint16(netreq->response + GLDNS_NSCOUNT_OFF, 0); gldns_write_uint16(netreq->response + GLDNS_ARCOUNT_OFF, 0); GLDNS_OPCODE_SET(netreq->response, 3); GLDNS_QR_SET(netreq->response); GLDNS_RD_SET(netreq->response); GLDNS_RA_SET(netreq->response); GLDNS_RCODE_SET(netreq->response, rcode); (void) memcpy( netreq->response + GLDNS_HEADER_SIZE , netreq->owner->name, netreq->owner->name_len); gldns_write_uint16( netreq->response + GLDNS_HEADER_SIZE + netreq->owner->name_len , netreq->request_type); gldns_write_uint16( netreq->response + GLDNS_HEADER_SIZE + netreq->owner->name_len + 2 , netreq->owner->request_class); netreq->response_len = GLDNS_HEADER_SIZE + netreq->owner->name_len + 4; return GETDNS_RETURN_GOOD; } #endif getdns_return_t _getdns_validate_dname(const char* dname) { int len; int label_len; const char* s; if (dname == NULL) { return GETDNS_RETURN_INVALID_PARAMETER; } len = strlen(dname); if (len > GETDNS_MAX_DNAME_LEN * 4 || len == 0) { return GETDNS_RETURN_BAD_DOMAIN_NAME; } if (len == 1 && dname[0] == '.') { /* root is ok */ return GETDNS_RETURN_GOOD; } /* By specification [RFC1035] the total length of a DNS label is * restricted to 63 octets and must be larger than 0 (except for the * final root-label). The total length of a domain name (i.e., label * octets and label length octets) is restricted to 255 octets or less. * With a fully qualified domain name this includes the last label * length octet for the root label. In a normalized representation the * number of labels (including the root) plus the number of octets in * each label may not be larger than 255. */ len = 0; label_len = 0; for (s = dname; *s; ++s) { switch (*s) { case '.': if (label_len > GETDNS_MAX_LABEL_LEN || label_len == 0) { return GETDNS_RETURN_BAD_DOMAIN_NAME; } label_len = 0; len += 1; break; case '\\': s += 1; if (isdigit(s[0])) { /* octet value */ if (! isdigit(s[1]) && ! isdigit(s[2])) return GETDNS_RETURN_BAD_DOMAIN_NAME; if ((s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0') > 255) return GETDNS_RETURN_BAD_DOMAIN_NAME; s += 2; } /* else literal char (1 octet) */ label_len++; len += 1; break; default: label_len++; len += 1; break; } } if (len > GETDNS_MAX_DNAME_LEN || label_len > GETDNS_MAX_LABEL_LEN) { return GETDNS_RETURN_BAD_DOMAIN_NAME; } return GETDNS_RETURN_GOOD; } /* _getdns_validate_dname */ static void _getdns_reply2wire_buf(gldns_buffer *buf, const getdns_dict *reply) { getdns_dict *rr_dict, *q_dict, *h_dict; getdns_list *section; size_t i, pkt_start; uint16_t ancount, nscount; uint32_t qtype, qclass = GETDNS_RRCLASS_IN, rcode = GETDNS_RCODE_NOERROR; getdns_bindata *qname; pkt_start = gldns_buffer_position(buf); /* Empty header */ gldns_buffer_write_u32(buf, 0); gldns_buffer_write_u32(buf, 0); gldns_buffer_write_u32(buf, 0); if ( !getdns_dict_get_dict(reply, "question", &q_dict) && !getdns_dict_get_int(q_dict, "qtype", &qtype) && !getdns_dict_get_bindata(q_dict, "qname", &qname)) { gldns_buffer_write(buf, qname->data, qname->size); gldns_buffer_write_u16(buf, (uint16_t)qtype); gldns_buffer_write_u16(buf, (uint16_t)qclass); gldns_buffer_write_u16_at( buf, pkt_start + GLDNS_QDCOUNT_OFF, 1); } if ( !getdns_dict_get_dict(reply, "header", &h_dict) && !getdns_dict_get_int(h_dict, "rcode", &rcode)) { GLDNS_RCODE_SET(gldns_buffer_at(buf, pkt_start), rcode); } if (!getdns_dict_get_list(reply, "answer", §ion)) { for ( i = 0, ancount = 0 ; !getdns_list_get_dict(section, i, &rr_dict) ; i++ ) { if (!_getdns_rr_dict2wire(rr_dict, buf)) ancount++; } gldns_buffer_write_u16_at( buf, pkt_start + GLDNS_ANCOUNT_OFF, ancount); } if (!getdns_dict_get_list(reply, "authority", §ion)) { for ( i = 0, nscount = 0 ; !getdns_list_get_dict(section, i, &rr_dict) ; i++ ) { if (!_getdns_rr_dict2wire(rr_dict, buf)) nscount++; } gldns_buffer_write_u16_at( buf, pkt_start + GLDNS_NSCOUNT_OFF, nscount); } } static void _getdns_list2wire_buf(gldns_buffer *buf, const getdns_list *l) { getdns_dict *rr_dict; size_t i, pkt_start; uint16_t ancount; uint32_t qtype, qclass = GETDNS_RRCLASS_IN; getdns_bindata *qname; pkt_start = gldns_buffer_position(buf); /* Empty header */ gldns_buffer_write_u32(buf, 0); gldns_buffer_write_u32(buf, 0); gldns_buffer_write_u32(buf, 0); for ( i = 0 ; !getdns_list_get_dict(l, i, &rr_dict) ; i++ ) { if (getdns_dict_get_int(rr_dict, "qtype", &qtype) || getdns_dict_get_bindata(rr_dict, "qname", &qname)) continue; (void) getdns_dict_get_int(rr_dict, "qclass", &qclass); gldns_buffer_write(buf, qname->data, qname->size); gldns_buffer_write_u16(buf, (uint16_t)qtype); gldns_buffer_write_u16(buf, (uint16_t)qclass); gldns_buffer_write_u16_at(buf, pkt_start+GLDNS_QDCOUNT_OFF, 1); break; } for ( i = 0, ancount = 0 ; !getdns_list_get_dict(l, i, &rr_dict) ; i++ ) { if (!_getdns_rr_dict2wire(rr_dict, buf)) ancount++; } gldns_buffer_write_u16_at(buf, pkt_start+GLDNS_ANCOUNT_OFF, ancount); } uint8_t *_getdns_list2wire(const getdns_list *l, uint8_t *buf, size_t *buf_len, const struct mem_funcs *mf) { gldns_buffer gbuf; size_t sz; gldns_buffer_init_vfixed_frm_data(&gbuf, buf, *buf_len); _getdns_list2wire_buf(&gbuf, l); if ((sz = gldns_buffer_position(&gbuf)) <= *buf_len) { *buf_len = sz; return buf; } if (!(buf = GETDNS_XMALLOC(*mf, uint8_t, (*buf_len = sz)))) return NULL; gldns_buffer_init_frm_data(&gbuf, buf, sz); _getdns_list2wire_buf(&gbuf, l); return buf; } uint8_t *_getdns_reply2wire(const getdns_dict *r, uint8_t *buf, size_t *buf_len, const struct mem_funcs *mf) { gldns_buffer gbuf; size_t sz; gldns_buffer_init_vfixed_frm_data(&gbuf, buf, *buf_len); _getdns_reply2wire_buf(&gbuf, r); if ((sz = gldns_buffer_position(&gbuf)) <= *buf_len) { *buf_len = sz; return buf; } if (!(buf = GETDNS_XMALLOC(*mf, uint8_t, (*buf_len = sz)))) return NULL; gldns_buffer_init_frm_data(&gbuf, buf, sz); _getdns_reply2wire_buf(&gbuf, r); return buf; } void _getdns_wire2list(const uint8_t *pkt, size_t pkt_len, getdns_list *l) { _getdns_rr_iter rr_spc, *rr; getdns_dict *rr_dict; for ( rr = _getdns_rr_iter_init(&rr_spc, pkt, pkt_len) ; rr ; rr = _getdns_rr_iter_next(rr)) { if (!(rr_dict = _getdns_rr_iter2rr_dict(&l->mf, rr))) continue; if (_getdns_list_append_this_dict(l, rr_dict)) getdns_dict_destroy(rr_dict); } } const char * _getdns_auth_str(getdns_auth_state_t auth) { static const char* getdns_auth_str_array[] = { GETDNS_STR_AUTH_NONE, GETDNS_STR_AUTH_FAILED, GETDNS_STR_AUTH_OK }; return getdns_auth_str_array[auth]; } /* util-internal.c */ getdns-1.5.1/src/platform.c0000644000175000017500000002032313416117763012513 00000000000000/** * * \file platform.c * @brief general functions with platform-dependent implementations * */ /* * Copyright (c) 2017, NLnet Labs, Sinodun * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 "platform.h" #include #ifdef USE_WINSOCK void _getdns_perror(const char *str) { char msg[256]; int errid = WSAGetLastError(); *msg = '\0'; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errid, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), msg, sizeof(msg), NULL); if (*msg == '\0') sprintf(msg, "Unknown error: %d", errid); if (str && *str != '\0') fprintf(stderr, "%s: ", str); fputs(msg, stderr); } const char *_getdns_strerror(DWORD errnum) { static char unknown[32]; switch(errnum) { case WSA_INVALID_HANDLE: return "Specified event object handle is invalid."; case WSA_NOT_ENOUGH_MEMORY: return "Insufficient memory available."; case WSA_INVALID_PARAMETER: return "One or more parameters are invalid."; case WSA_OPERATION_ABORTED: return "Overlapped operation aborted."; case WSA_IO_INCOMPLETE: return "Overlapped I/O event object not in signaled state."; case WSA_IO_PENDING: return "Overlapped operations will complete later."; case WSAEINTR: return "Interrupted function call."; case WSAEBADF: return "File handle is not valid."; case WSAEACCES: return "Permission denied."; case WSAEFAULT: return "Bad address."; case WSAEINVAL: return "Invalid argument."; case WSAEMFILE: return "Too many open files."; case WSAEWOULDBLOCK: return "Resource temporarily unavailable."; case WSAEINPROGRESS: return "Operation now in progress."; case WSAEALREADY: return "Operation already in progress."; case WSAENOTSOCK: return "Socket operation on nonsocket."; case WSAEDESTADDRREQ: return "Destination address required."; case WSAEMSGSIZE: return "Message too long."; case WSAEPROTOTYPE: return "Protocol wrong type for socket."; case WSAENOPROTOOPT: return "Bad protocol option."; case WSAEPROTONOSUPPORT: return "Protocol not supported."; case WSAESOCKTNOSUPPORT: return "Socket type not supported."; case WSAEOPNOTSUPP: return "Operation not supported."; case WSAEPFNOSUPPORT: return "Protocol family not supported."; case WSAEAFNOSUPPORT: return "Address family not supported by protocol family."; case WSAEADDRINUSE: return "Address already in use."; case WSAEADDRNOTAVAIL: return "Cannot assign requested address."; case WSAENETDOWN: return "Network is down."; case WSAENETUNREACH: return "Network is unreachable."; case WSAENETRESET: return "Network dropped connection on reset."; case WSAECONNABORTED: return "Software caused connection abort."; case WSAECONNRESET: return "Connection reset by peer."; case WSAENOBUFS: return "No buffer space available."; case WSAEISCONN: return "Socket is already connected."; case WSAENOTCONN: return "Socket is not connected."; case WSAESHUTDOWN: return "Cannot send after socket shutdown."; case WSAETOOMANYREFS: return "Too many references."; case WSAETIMEDOUT: return "Connection timed out."; case WSAECONNREFUSED: return "Connection refused."; case WSAELOOP: return "Cannot translate name."; case WSAENAMETOOLONG: return "Name too long."; case WSAEHOSTDOWN: return "Host is down."; case WSAEHOSTUNREACH: return "No route to host."; case WSAENOTEMPTY: return "Directory not empty."; case WSAEPROCLIM: return "Too many processes."; case WSAEUSERS: return "User quota exceeded."; case WSAEDQUOT: return "Disk quota exceeded."; case WSAESTALE: return "Stale file handle reference."; case WSAEREMOTE: return "Item is remote."; case WSASYSNOTREADY: return "Network subsystem is unavailable."; case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range."; case WSANOTINITIALISED: return "Successful WSAStartup not yet performed."; case WSAEDISCON: return "Graceful shutdown in progress."; case WSAENOMORE: return "No more results."; case WSAECANCELLED: return "Call has been canceled."; case WSAEINVALIDPROCTABLE: return "Procedure call table is invalid."; case WSAEINVALIDPROVIDER: return "Service provider is invalid."; case WSAEPROVIDERFAILEDINIT: return "Service provider failed to initialize."; case WSASYSCALLFAILURE: return "System call failure."; case WSASERVICE_NOT_FOUND: return "Service not found."; case WSATYPE_NOT_FOUND: return "Class type not found."; case WSA_E_NO_MORE: return "No more results."; case WSA_E_CANCELLED: return "Call was canceled."; case WSAEREFUSED: return "Database query was refused."; case WSAHOST_NOT_FOUND: return "Host not found."; case WSATRY_AGAIN: return "Nonauthoritative host not found."; case WSANO_RECOVERY: return "This is a nonrecoverable error."; case WSANO_DATA: return "Valid name, no data record of requested type."; case WSA_QOS_RECEIVERS: return "QOS receivers."; case WSA_QOS_SENDERS: return "QOS senders."; case WSA_QOS_NO_SENDERS: return "No QOS senders."; case WSA_QOS_NO_RECEIVERS: return "QOS no receivers."; case WSA_QOS_REQUEST_CONFIRMED: return "QOS request confirmed."; case WSA_QOS_ADMISSION_FAILURE: return "QOS admission error."; case WSA_QOS_POLICY_FAILURE: return "QOS policy failure."; case WSA_QOS_BAD_STYLE: return "QOS bad style."; case WSA_QOS_BAD_OBJECT: return "QOS bad object."; case WSA_QOS_TRAFFIC_CTRL_ERROR: return "QOS traffic control error."; case WSA_QOS_GENERIC_ERROR: return "QOS generic error."; case WSA_QOS_ESERVICETYPE: return "QOS service type error."; case WSA_QOS_EFLOWSPEC: return "QOS flowspec error."; case WSA_QOS_EPROVSPECBUF: return "Invalid QOS provider buffer."; case WSA_QOS_EFILTERSTYLE: return "Invalid QOS filter style."; case WSA_QOS_EFILTERTYPE: return "Invalid QOS filter type."; case WSA_QOS_EFILTERCOUNT: return "Incorrect QOS filter count."; case WSA_QOS_EOBJLENGTH: return "Invalid QOS object length."; case WSA_QOS_EFLOWCOUNT: return "Incorrect QOS flow count."; /*case WSA_QOS_EUNKOWNPSOBJ: return "Unrecognized QOS object.";*/ case WSA_QOS_EPOLICYOBJ: return "Invalid QOS policy object."; case WSA_QOS_EFLOWDESC: return "Invalid QOS flow descriptor."; case WSA_QOS_EPSFLOWSPEC: return "Invalid QOS provider-specific flowspec."; case WSA_QOS_EPSFILTERSPEC: return "Invalid QOS provider-specific filterspec."; case WSA_QOS_ESDMODEOBJ: return "Invalid QOS shape discard mode object."; case WSA_QOS_ESHAPERATEOBJ: return "Invalid QOS shaping rate object."; case WSA_QOS_RESERVED_PETYPE: return "Reserved policy QOS element type."; default: snprintf(unknown, sizeof(unknown), "unknown WSA error code %d", (int)errnum); return unknown; } } #else void _getdns_perror(const char *str) { perror(str); } const char *_getdns_strerror(int errnum) { return strerror(errnum); } #endif getdns-1.5.1/src/convert.h0000644000175000017500000000476313416117763012366 00000000000000/** * * \file convert.h * @brief getdns label conversion functions * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef _GETDNS_CONVERT_H_ #define _GETDNS_CONVERT_H_ #include "types-internal.h" #include getdns_return_t _getdns_wire2rr_dict(struct mem_funcs *mf, const uint8_t *wire, size_t wire_len, getdns_dict **rr_dict); getdns_return_t _getdns_wire2rr_dict_buf(struct mem_funcs *mf, const uint8_t *wire, size_t *wire_len, getdns_dict **rr_dict); getdns_return_t _getdns_wire2rr_dict_scan(struct mem_funcs *mf, const uint8_t **wire, size_t *wire_len, getdns_dict **rr_dict); getdns_return_t _getdns_str2rr_dict(struct mem_funcs *mf, const char *str, getdns_dict **rr_dict, const char *origin, uint32_t default_ttl); getdns_return_t _getdns_fp2rr_list(struct mem_funcs *mf, FILE *in, getdns_list **rr_list, const char *origin, uint32_t default_ttl); getdns_return_t _getdns_reply_dict2wire( const getdns_dict *reply, gldns_buffer *buf, int reuse_header); #endif /* convert.h */ getdns-1.5.1/src/ub_loop.c0000644000175000017500000003056513416117763012337 00000000000000/** * * \file ub_loop.c * @brief Interface to the unbound pluggable event API * * These routines are not intended to be used by applications calling into * the library. * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 "ub_loop.h" #ifdef HAVE_UNBOUND_EVENT_API #define UB_EVENT_API_MAGIC 0x44d74d78 #ifndef HAVE_UNBOUND_EVENT_H /** event timeout */ #define UB_EV_TIMEOUT 0x01 /** event fd readable */ #define UB_EV_READ 0x02 /** event fd writable */ #define UB_EV_WRITE 0x04 /** event signal */ #define UB_EV_SIGNAL 0x08 /** event must persist */ #define UB_EV_PERSIST 0x10 struct ub_event_base_vmt { void (*free)(struct ub_event_base*); int (*dispatch)(struct ub_event_base*); int (*loopexit)(struct ub_event_base*, struct timeval*); struct ub_event* (*new_event)(struct ub_event_base*, int fd, short bits, void (*cb)(int, short, void*), void* arg); struct ub_event* (*new_signal)(struct ub_event_base*, int fd, void (*cb)(int, short, void*), void* arg); struct ub_event* (*winsock_register_wsaevent)(struct ub_event_base*, void* wsaevent, void (*cb)(int, short, void*), void* arg); }; struct ub_event_vmt { void (*add_bits)(struct ub_event*, short); void (*del_bits)(struct ub_event*, short); void (*set_fd)(struct ub_event*, int); void (*free)(struct ub_event*); int (*add)(struct ub_event*, struct timeval*); int (*del)(struct ub_event*); int (*add_timer)(struct ub_event*, struct ub_event_base*, void (*cb)(int, short, void*), void* arg, struct timeval*); int (*del_timer)(struct ub_event*); int (*add_signal)(struct ub_event*, struct timeval*); int (*del_signal)(struct ub_event*); void (*winsock_unregister_wsaevent)(struct ub_event* ev); void (*winsock_tcp_wouldblock)(struct ub_event*, int eventbit); }; struct ub_event { unsigned long magic; struct ub_event_vmt* vmt; }; #endif typedef struct my_event { struct ub_event super; /** event in the getdns event loop */ getdns_eventloop_event gev; /** is event already added */ int added; /** event loop it belongs to */ _getdns_ub_loop *loop; /** fd to poll or -1 for timeouts. signal number for sigs. */ int fd; /** what events this event is interested in, see EV_.. above. */ short bits; /** timeout value */ uint64_t timeout; /** callback to call: fd, eventbits, userarg */ void (*cb)(int, short, void *arg); /** callback user arg */ void *arg; #ifdef USE_WINSOCK int is_tcp; int read_wouldblock; int write_wouldblock; #endif int *active; } my_event; #define AS_UB_LOOP(x) \ ((_getdns_ub_loop *)(x)) #define AS_MY_EVENT(x) \ ((my_event *)(x)) static void my_event_base_free(struct ub_event_base* base) { /* We don't allocate our event base, so no need to free */ (void)base; return; } static int my_event_base_dispatch(struct ub_event_base* base) { (void)base; /* We run the event loop extension for which this ub_event_base is an * interface ourselfs, so no need to let libunbound call dispatch. */ DEBUG_SCHED("UB_LOOP ERROR: my_event_base_dispatch()\n"); return -1; } static int my_event_base_loopexit(struct ub_event_base* base, struct timeval* tv) { (void)tv; /* Not sure when this will be called. But it is of no influence as we * run the event loop ourself. */ AS_UB_LOOP(base)->running = 0; return 0; } static void clear_my_event(my_event *ev) { DEBUG_SCHED("UB_LOOP: to clear %p(%d, %d, %"PRIu64"), total: %d\n" , (void *)ev, ev->fd, ev->bits, ev->timeout, ev->loop->n_events); (ev)->loop->extension->vmt->clear((ev)->loop->extension, &(ev)->gev); (ev)->added = 0; if ((ev)->active) { *(ev)->active = 0; (ev)->active = NULL; } DEBUG_SCHED("UB_LOOP: %p(%d, %d, %"PRIu64") cleared, total: %d\n" , (void *)ev, ev->fd, ev->bits, ev->timeout, --ev->loop->n_events); } static getdns_return_t schedule_my_event(my_event *ev) { getdns_return_t r; DEBUG_SCHED("UB_LOOP: to schedule %p(%d, %d, %"PRIu64"), total: %d\n" , (void *)ev, ev->fd, ev->bits, ev->timeout, ev->loop->n_events); if (ev->gev.read_cb || ev->gev.write_cb || ev->gev.timeout_cb) { if ((r = ev->loop->extension->vmt->schedule( ev->loop->extension, ev->fd, ev->timeout, &ev->gev))) { DEBUG_SCHED("UB_LOOP ERROR: scheduling event: %p\n", (void *)ev); return r; } ev->added = 1; DEBUG_SCHED("UB_LOOP: event %p(%d, %d, %"PRIu64") scheduled, " "total: %d\n", (void *)ev, ev->fd, ev->bits, ev->timeout , ++ev->loop->n_events); } return GETDNS_RETURN_GOOD; } static void read_cb(void *userarg) { struct my_event *ev = (struct my_event *)userarg; int active = 1; ev->active = &active; #ifdef USE_WINSOCK if (ev->is_tcp) { ev->read_wouldblock = 0; do { (*ev->cb)(ev->fd, UB_EV_READ, ev->arg); } while (active && !ev->read_wouldblock && (ev->bits & UB_EV_PERSIST)); } else (*ev->cb)(ev->fd, UB_EV_READ, ev->arg); #else (*ev->cb)(ev->fd, UB_EV_READ, ev->arg); #endif if (active) { ev->active = NULL; if ((ev->bits & UB_EV_PERSIST) == 0) clear_my_event(ev); } } static void write_cb(void *userarg) { struct my_event *ev = (struct my_event *)userarg; int active = 1; ev->active = &active; #ifdef USE_WINSOCK if (ev->is_tcp) { ev->write_wouldblock = 0; do { (*ev->cb)(ev->fd, UB_EV_WRITE, ev->arg); } while (active && !ev->write_wouldblock && (ev->bits & UB_EV_PERSIST)); } else (*ev->cb)(ev->fd, UB_EV_WRITE, ev->arg); #else (*ev->cb)(ev->fd, UB_EV_WRITE, ev->arg); #endif if (active) { ev->active = NULL; if ((ev->bits & UB_EV_PERSIST) == 0) clear_my_event(ev); } } static void timeout_cb(void *userarg) { struct my_event *ev = (struct my_event *)userarg; int active = 1; ev->active = &active; (*ev->cb)(ev->fd, UB_EV_TIMEOUT, ev->arg); if (active) { ev->active = NULL; if ((ev->bits & UB_EV_PERSIST) == 0) clear_my_event(ev); } } static getdns_return_t set_gev_callbacks(my_event* ev, short bits) { int added = ev->added; if (ev->bits != bits) { if (added) clear_my_event(ev); ev->gev.read_cb = bits & UB_EV_READ ? read_cb : NULL; ev->gev.write_cb = bits & UB_EV_WRITE ? write_cb : NULL; ev->gev.timeout_cb = bits & UB_EV_TIMEOUT ? timeout_cb : NULL; ev->bits = bits; if (added) return schedule_my_event(ev); } return GETDNS_RETURN_GOOD; } static void my_event_add_bits(struct ub_event* ev, short bits) { (void) set_gev_callbacks(AS_MY_EVENT(ev), AS_MY_EVENT(ev)->bits | bits); } static void my_event_del_bits(struct ub_event* ev, short bits) { (void) set_gev_callbacks(AS_MY_EVENT(ev), AS_MY_EVENT(ev)->bits & ~bits); } static void my_event_set_fd(struct ub_event* ub_ev, int fd) { my_event *ev = AS_MY_EVENT(ub_ev); if (ev->fd != fd) { if (ev->added) { clear_my_event(ev); ev->fd = fd; (void) schedule_my_event(ev); } else ev->fd = fd; } } static void my_event_free(struct ub_event* ev) { GETDNS_FREE(AS_MY_EVENT(ev)->loop->mf, ev); } static int my_event_del(struct ub_event* ev) { if (AS_MY_EVENT(ev)->added) clear_my_event(AS_MY_EVENT(ev)); return 0; } static int my_event_add(struct ub_event* ub_ev, struct timeval* tv) { my_event *ev = AS_MY_EVENT(ub_ev); #ifdef USE_WINSOCK int t, l = sizeof(t); #endif if (ev->added) my_event_del(&ev->super); if (tv && (ev->bits & UB_EV_TIMEOUT) != 0) ev->timeout = (tv->tv_sec * 1000) + (tv->tv_usec / 1000); #ifdef USE_WINSOCK if ((ev->bits & (UB_EV_READ|UB_EV_WRITE)) && ev->fd != -1 && getsockopt(ev->fd, SOL_SOCKET, SO_TYPE, (void *)&t, &l) == 0 && t == SOCK_STREAM) { ev->is_tcp = 1; ev->read_wouldblock = 0; ev->write_wouldblock = 0; } else ev->is_tcp = 0; #endif if (schedule_my_event(AS_MY_EVENT(ev))) return -1; return 0; } static int my_timer_add(struct ub_event* ub_ev, struct ub_event_base* base, void (*cb)(int, short, void*), void* arg, struct timeval* tv) { my_event *ev = AS_MY_EVENT(ub_ev); if (!base || !cb || !tv || AS_UB_LOOP(base) != ev->loop) { DEBUG_SCHED("UB_LOOP ERROR: my_timer_add()\n"); return -1; } if (ev->added) clear_my_event(ev); ev->cb = cb; ev->arg = arg; return my_event_add(ub_ev, tv); } static int my_timer_del(struct ub_event* ev) { return my_event_del(ev); } static int my_signal_add(struct ub_event* ub_ev, struct timeval* tv) { (void)ub_ev; (void)tv; /* Only unbound daaemon workers use signals */ DEBUG_SCHED("UB_LOOP ERROR: signal_add()\n"); return -1; } static int my_signal_del(struct ub_event* ub_ev) { (void)ub_ev; /* Only unbound daaemon workers use signals */ DEBUG_SCHED("UB_LOOP ERROR: signal_del()\n"); return -1; } static void my_winsock_unregister_wsaevent(struct ub_event* ev) { /* wsa events don't get registered with libunbound */ (void)ev; } static void my_winsock_tcp_wouldblock(struct ub_event* ev, int bits) { #ifndef USE_WINSOCK (void)ev; (void)bits; #else if (bits & UB_EV_READ) AS_MY_EVENT(ev)->read_wouldblock = 1; if (bits & UB_EV_WRITE) AS_MY_EVENT(ev)->write_wouldblock = 1; #endif } static struct ub_event* my_event_new(struct ub_event_base* base, int fd, short bits, void (*cb)(int, short, void*), void* arg) { static struct ub_event_vmt vmt = { my_event_add_bits, my_event_del_bits, my_event_set_fd, my_event_free, my_event_add, my_event_del, my_timer_add, my_timer_del, my_signal_add, my_signal_del, my_winsock_unregister_wsaevent, my_winsock_tcp_wouldblock }; my_event *ev; if (!base || !cb) return NULL; ev = GETDNS_MALLOC(AS_UB_LOOP(base)->mf, my_event); ev->super.magic = UB_EVENT_API_MAGIC; ev->super.vmt = &vmt; ev->loop = AS_UB_LOOP(base); ev->added = 0; ev->fd = fd; ev->bits = bits; ev->timeout = TIMEOUT_FOREVER; ev->cb = cb; ev->arg = arg; #ifdef USE_WINSOCK ev->is_tcp = 0; ev->read_wouldblock = 0; ev->write_wouldblock = 0; #endif ev->active = NULL; ev->gev.userarg = ev; ev->gev.read_cb = bits & UB_EV_READ ? read_cb : NULL; ev->gev.write_cb = bits & UB_EV_WRITE ? write_cb : NULL; ev->gev.timeout_cb = bits & UB_EV_TIMEOUT ? timeout_cb : NULL; return &ev->super; } static struct ub_event* my_signal_new(struct ub_event_base* base, int fd, void (*cb)(int, short, void*), void* arg) { /* Not applicable, because in unbound used in the daemon only */ (void)base; (void)fd; (void)cb; (void)arg; return NULL; } static struct ub_event* my_winsock_register_wsaevent(struct ub_event_base *b, void* wsaevent, void (*cb)(int, short, void*), void* arg) { /* Not applicable, because in unbound used for tubes only */ (void)b; (void)wsaevent; (void)cb; (void)arg; return NULL; } void _getdns_ub_loop_init(_getdns_ub_loop *loop, struct mem_funcs *mf, getdns_eventloop *extension) { static struct ub_event_base_vmt vmt = { my_event_base_free, my_event_base_dispatch, my_event_base_loopexit, my_event_new, my_signal_new, my_winsock_register_wsaevent }; loop->super.magic = UB_EVENT_API_MAGIC; loop->super.vmt = &vmt; loop->mf = *mf; loop->extension = extension; loop->running = 1; #if defined(SCHED_DEBUG) && SCHED_DEBUG loop->n_events = 0; #endif } #endif /* ub_loop.c */ getdns-1.5.1/src/const-info.h0000644000175000017500000000473013416117763012757 00000000000000/** * * /brief _getdns_consts table with values, names and descriptions of the * constants in getdns * * The _getdns_get_validation_chain function is called after an answer * has been fetched when the dnssec_return_validation_chain extension is set. * It fetches DNSKEYs, DSes and their signatures for all RRSIGs found in the * answer. */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef CONST_INFO_H_ #define CONST_INFO_H_ #include "getdns/getdns.h" #include "getdns/getdns_extra.h" #ifndef GETDNS_CONTEXT_CODE_MAX_BACKOFF_VALUE #define GETDNS_CONTEXT_CODE_MAX_BACKOFF_VALUE 699 #define GETDNS_CONTEXT_CODE_MAX_BACKOFF_VALUE_TEXT "Change related to getdns_context_set_max_backoff_value" #endif struct const_info { int code; const char *name; const char *text; }; struct const_info *_getdns_get_const_info(int value); struct const_name_info { const char *name; uint32_t code; }; int _getdns_get_const_name_info(const char *name, uint32_t *code); #endif /* const-info.h */ getdns-1.5.1/src/request-internal.c0000644000175000017500000010623313416117763014176 00000000000000/** * * /brief getdns contect management functions * * This is the meat of the API * Originally taken from the getdns API description pseudo implementation. * */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 "config.h" #include "types-internal.h" #include "util-internal.h" #include "gldns/rrdef.h" #include "gldns/str2wire.h" #include "gldns/gbuffer.h" #include "gldns/pkthdr.h" #include "dict.h" #include "debug.h" #include "convert.h" #include "general.h" /* MAXIMUM_TSIG_SPACE = TSIG name (dname) : 256 * TSIG type (uint16_t) : 2 * TSIG class (uint16_t) : 2 * TSIG TTL (uint32_t) : 4 * RdLen (uint16_t) : 2 * Algorithm name (dname) : 256 * Time Signed (uint48_t) : 6 * Fudge (uint16_t) : 2 * Mac Size (uint16_t) : 2 * Mac (variable) : EVP_MAX_MD_SIZE * Original Id (uint16_t) : 2 * Error (uint16_t) : 2 * Other Len (uint16_t) : 2 * Other Data (nothing) : 0 * ---- + * 538 + EVP_MAX_MD_SIZE */ #define MAXIMUM_TSIG_SPACE (538 + EVP_MAX_MD_SIZE) getdns_dict dnssec_ok_checking_disabled_spc = { { RBTREE_NULL, 0, (int (*)(const void *, const void *)) strcmp }, { NULL, {{ NULL, NULL, NULL }}} }; getdns_dict *dnssec_ok_checking_disabled = &dnssec_ok_checking_disabled_spc; getdns_dict dnssec_ok_checking_disabled_roadblock_avoidance_spc = { { RBTREE_NULL, 0, (int (*)(const void *, const void *)) strcmp }, { NULL, {{ NULL, NULL, NULL }}} }; getdns_dict *dnssec_ok_checking_disabled_roadblock_avoidance = &dnssec_ok_checking_disabled_roadblock_avoidance_spc; getdns_dict dnssec_ok_checking_disabled_avoid_roadblocks_spc = { { RBTREE_NULL, 0, (int (*)(const void *, const void *)) strcmp }, { NULL, {{ NULL, NULL, NULL }}} }; getdns_dict *dnssec_ok_checking_disabled_avoid_roadblocks = &dnssec_ok_checking_disabled_avoid_roadblocks_spc; getdns_dict no_dnssec_checking_disabled_opportunistic_spc = { { RBTREE_NULL, 0, (int (*)(const void *, const void *)) strcmp }, { NULL, {{ NULL, NULL, NULL }}} }; getdns_dict *no_dnssec_checking_disabled_opportunistic = &no_dnssec_checking_disabled_opportunistic_spc; static int is_extension_set(const getdns_dict *extensions, const char *name, int default_value) { getdns_return_t r; uint32_t value; if ( ! extensions || extensions == dnssec_ok_checking_disabled || extensions == dnssec_ok_checking_disabled_roadblock_avoidance || extensions == dnssec_ok_checking_disabled_avoid_roadblocks || extensions == no_dnssec_checking_disabled_opportunistic) return 0; r = getdns_dict_get_int(extensions, name, &value); return r == GETDNS_RETURN_GOOD ? ( value == GETDNS_EXTENSION_TRUE ) : default_value; } static void network_req_cleanup(getdns_network_req *net_req) { assert(net_req); if (net_req->query_id_registered) { (void) _getdns_rbtree_delete( net_req->query_id_registered, net_req->node.key); net_req->query_id_registered = NULL; net_req->node.key = NULL; } if (net_req->response && (net_req->response < net_req->wire_data || net_req->response > net_req->wire_data+ net_req->wire_data_sz)) GETDNS_FREE(net_req->owner->my_mf, net_req->response); if (net_req->debug_tls_peer_cert.size && net_req->debug_tls_peer_cert.data) OPENSSL_free(net_req->debug_tls_peer_cert.data); } static uint8_t * netreq_reset(getdns_network_req *net_req) { uint8_t *buf; /* variables that need to be reset on reinit */ net_req->first_upstream = NULL; net_req->unbound_id = -1; _getdns_netreq_change_state(net_req, NET_REQ_NOT_SENT); if (net_req->query_id_registered) { (void) _getdns_rbtree_delete(net_req->query_id_registered, (void *)(intptr_t)GLDNS_ID_WIRE(net_req->query)); net_req->query_id_registered = NULL; net_req->node.key = NULL; } net_req->dnssec_status = GETDNS_DNSSEC_INDETERMINATE; net_req->tsig_status = GETDNS_DNSSEC_INDETERMINATE; net_req->response_len = 0; /* Some fields to record info for return_call_reporting */ net_req->debug_start_time = 0; net_req->debug_end_time = 0; if (!net_req->query) return NULL; buf = net_req->query + GLDNS_HEADER_SIZE; (void) memcpy(buf, net_req->owner->name, net_req->owner->name_len); buf += net_req->owner->name_len; gldns_write_uint16(buf, net_req->request_type); gldns_write_uint16(buf + 2, net_req->owner->request_class); return buf + 4; } static int network_req_init(getdns_network_req *net_req, getdns_dns_req *owner, uint16_t request_type, int checking_disabled, int opportunistic, int with_opt, int edns_maximum_udp_payload_size, uint8_t edns_extended_rcode, uint8_t edns_version, int edns_do_bit, uint16_t opt_options_size, size_t noptions, getdns_list *options, size_t wire_data_sz, size_t max_query_sz, const getdns_dict *extensions) { uint8_t *buf; getdns_dict *option; uint32_t option_code; getdns_bindata *option_data; size_t i; int r = 0; gldns_buffer gbuf; /* variables that stay the same on reinit, don't touch */ net_req->request_type = request_type; net_req->owner = owner; net_req->edns_maximum_udp_payload_size = edns_maximum_udp_payload_size; net_req->max_udp_payload_size = edns_maximum_udp_payload_size != -1 ? edns_maximum_udp_payload_size : 1432; net_req->base_query_option_sz = opt_options_size; net_req->wire_data_sz = wire_data_sz; net_req->transport_count = owner->context->dns_transport_count; memcpy(net_req->transports, owner->context->dns_transports, net_req->transport_count * sizeof(getdns_transport_list_t)); net_req->tls_auth_min = owner->context->tls_auth == GETDNS_AUTHENTICATION_REQUIRED && owner->context->dns_transport_count == 1 && owner->context->dns_transports[0] == GETDNS_TRANSPORT_TLS && !opportunistic ? GETDNS_AUTHENTICATION_REQUIRED : GETDNS_AUTHENTICATION_NONE; net_req->follow_redirects = owner->context->follow_redirects; /* state variables from the resolver, don't touch */ net_req->upstream = NULL; net_req->fd = -1; net_req->transport_current = 0; memset(&net_req->event, 0, sizeof(net_req->event)); net_req->keepalive_sent = 0; net_req->write_queue_tail = NULL; /* Some fields to record info for return_call_reporting */ net_req->debug_tls_auth_status = GETDNS_AUTH_NONE; net_req->debug_tls_peer_cert.size = 0; net_req->debug_tls_peer_cert.data = NULL; net_req->debug_tls_version = NULL; net_req->debug_udp = 0; /* Scheduling, touch only via _getdns_netreq_change_state! */ net_req->state = NET_REQ_NOT_SENT; /* A registered netreq (on a statefull transport) * Deregister on reset and cleanup. */ net_req->query_id_registered = NULL; net_req->node.key = NULL; if (max_query_sz == 0) { net_req->query = NULL; net_req->opt = NULL; net_req->response = net_req->wire_data; netreq_reset(net_req); return r; } /* first two bytes will contain query length (for tcp) */ net_req->query = net_req->wire_data + 2; buf = net_req->query; gldns_write_uint16(buf + 2, 0); /* reset all flags */ GLDNS_RD_SET(buf); GLDNS_OPCODE_SET(buf, GLDNS_PACKET_QUERY); gldns_write_uint16(buf + GLDNS_QDCOUNT_OFF, 1); /* 1 query */ gldns_write_uint16(buf + GLDNS_ANCOUNT_OFF, 0); /* 0 answers */ gldns_write_uint16(buf + GLDNS_NSCOUNT_OFF, 0); /* 0 authorities */ gldns_write_uint16(buf + GLDNS_ARCOUNT_OFF, with_opt ? 1 : 0); buf = netreq_reset(net_req); gldns_buffer_init_frm_data( &gbuf, net_req->query, net_req->wire_data_sz - 2); if (owner->context->header) _getdns_reply_dict2wire(owner->context->header, &gbuf, 1); gldns_buffer_rewind(&gbuf); _getdns_reply_dict2wire(extensions, &gbuf, 1); if (checking_disabled) /* We will do validation ourselves */ GLDNS_CD_SET(net_req->query); if (with_opt) { net_req->opt = buf; buf[0] = 0; /* dname for . */ gldns_write_uint16(buf + 1, GLDNS_RR_TYPE_OPT); gldns_write_uint16(net_req->opt + 3, net_req->max_udp_payload_size); buf[5] = edns_extended_rcode; buf[6] = edns_version; buf[7] = edns_do_bit ? 0x80 : 0; buf[8] = 0; gldns_write_uint16(buf + 9, opt_options_size); buf += 11; for (i = 0; i < noptions; i++) { if (getdns_list_get_dict(options, i, &option)) continue; if (getdns_dict_get_int( option, "option_code", &option_code)) continue; if (getdns_dict_get_bindata( option, "option_data", &option_data)) continue; gldns_write_uint16(buf, (uint16_t) option_code); gldns_write_uint16(buf + 2, (uint16_t) option_data->size); (void) memcpy(buf + 4, option_data->data, option_data->size); buf += option_data->size + 4; } } else net_req->opt = NULL; net_req->response = buf; gldns_write_uint16(net_req->wire_data, net_req->response - net_req->query); return r; } /* req->opt + 9 is the length; req->opt + 11 is the start of the options. clear_upstream_options() goes back to the per-query options. */ void _getdns_network_req_clear_upstream_options(getdns_network_req * req) { size_t pktlen; if (req->opt) { gldns_write_uint16(req->opt + 9, (uint16_t) req->base_query_option_sz); req->response = req->opt + 11 + req->base_query_option_sz; pktlen = req->response - req->query; gldns_write_uint16(req->query - 2, (uint16_t) pktlen); } } void _getdns_netreq_reinit(getdns_network_req *netreq) { uint8_t *base_opt_backup; size_t base_opt_rr_sz; if (!netreq->query) { (void) netreq_reset(netreq); return; } else if (!netreq->opt) { /* Remove TSIG (if any) */ gldns_write_uint16(netreq->query + GLDNS_ARCOUNT_OFF, 0); netreq->response = netreq_reset(netreq); gldns_write_uint16(netreq->wire_data, netreq->response - netreq->query); return; } _getdns_network_req_clear_upstream_options(netreq); base_opt_rr_sz = netreq->base_query_option_sz + 11; base_opt_backup = netreq->wire_data + netreq->wire_data_sz - base_opt_rr_sz; (void) memcpy(base_opt_backup, netreq->opt, base_opt_rr_sz); netreq->opt = netreq_reset(netreq); (void) memcpy(netreq->opt, base_opt_backup, base_opt_rr_sz); netreq->response = netreq->opt + base_opt_rr_sz; /* Remove TSIG (if any), but leave the opt RR */ gldns_write_uint16(netreq->query + GLDNS_ARCOUNT_OFF, 1); gldns_write_uint16(netreq->wire_data, netreq->response - netreq->query); } /* add_upstream_option appends an option that is derived at send time. (you can send data as NULL and it will fill with all zeros) */ getdns_return_t _getdns_network_req_add_upstream_option(getdns_network_req * req, uint16_t code, uint16_t sz, const void* data) { uint16_t oldlen; uint32_t newlen; uint32_t pktlen; size_t cur_upstream_option_sz; /* if no options are set, we can't add upstream options */ if (!req->opt) return GETDNS_RETURN_GENERIC_ERROR; /* if TCP, no overflow allowed for length field https://tools.ietf.org/html/rfc1035#section-4.2.2 */ pktlen = req->response - req->query; pktlen += 4 + sz; if (pktlen > UINT16_MAX) return GETDNS_RETURN_GENERIC_ERROR; /* no overflow allowed for OPT size either (maybe this is overkill given the above check?) */ oldlen = gldns_read_uint16(req->opt + 9); newlen = oldlen + 4 + sz; if (newlen > UINT16_MAX) return GETDNS_RETURN_GENERIC_ERROR; /* avoid overflowing MAXIMUM_UPSTREAM_OPTION_SPACE */ cur_upstream_option_sz = (size_t)oldlen - req->base_query_option_sz; if (cur_upstream_option_sz + 4 + sz > MAXIMUM_UPSTREAM_OPTION_SPACE) return GETDNS_RETURN_GENERIC_ERROR; /* actually add the option: */ gldns_write_uint16(req->opt + 11 + oldlen, code); gldns_write_uint16(req->opt + 11 + oldlen + 2, sz); if (data != NULL) memcpy(req->opt + 11 + oldlen + 4, data, sz); else memset(req->opt + 11 + oldlen + 4, 0, sz); gldns_write_uint16(req->opt + 9, newlen); /* the response should start right after the options end: */ req->response = req->opt + 11 + newlen; /* for TCP, adjust the size of the wire format itself: */ gldns_write_uint16(req->query - 2, pktlen); return GETDNS_RETURN_GOOD; } size_t _getdns_network_req_add_tsig(getdns_network_req *req) { getdns_upstream *upstream = req->upstream; gldns_buffer gbuf; uint16_t arcount; const getdns_tsig_info *tsig_info; uint8_t md_buf[EVP_MAX_MD_SIZE]; unsigned int md_len = EVP_MAX_MD_SIZE; const EVP_MD *digester; /* Should only be called when in stub mode */ assert(req->query); if (upstream->tsig_alg == GETDNS_NO_TSIG || !upstream->tsig_dname_len) return req->response - req->query; arcount = gldns_read_uint16(req->query + 10); #if defined(STUB_DEBUG) && STUB_DEBUG /* TSIG should not have been written yet. */ if (req->opt) { assert(arcount == 1); assert(req->opt + 11 + gldns_read_uint16(req->opt + 9) == req->response); } else assert(arcount == 0); #endif tsig_info = _getdns_get_tsig_info(upstream->tsig_alg); gldns_buffer_init_vfixed_frm_data(&gbuf, req->response, MAXIMUM_TSIG_SPACE); gldns_buffer_write(&gbuf, upstream->tsig_dname, upstream->tsig_dname_len); /* Name */ gldns_buffer_write_u16(&gbuf, GETDNS_RRCLASS_ANY); /* Class */ gldns_buffer_write_u32(&gbuf, 0); /* TTL */ gldns_buffer_write(&gbuf, tsig_info->dname, tsig_info->dname_len); /* Algorithm Name */ gldns_buffer_write_u48(&gbuf, time(NULL)); /* Time Signed */ gldns_buffer_write_u16(&gbuf, 300); /* Fudge */ gldns_buffer_write_u16(&gbuf, 0); /* Error */ gldns_buffer_write_u16(&gbuf, 0); /* Other len */ switch (upstream->tsig_alg) { #ifdef HAVE_EVP_MD5 case GETDNS_HMAC_MD5 : digester = EVP_md5() ; break; #endif #ifdef HAVE_EVP_SHA1 case GETDNS_HMAC_SHA1 : digester = EVP_sha1() ; break; #endif #ifdef HAVE_EVP_SHA224 case GETDNS_HMAC_SHA224: digester = EVP_sha224(); break; #endif #ifdef HAVE_EVP_SHA256 case GETDNS_HMAC_SHA256: digester = EVP_sha256(); break; #endif #ifdef HAVE_EVP_SHA384 case GETDNS_HMAC_SHA384: digester = EVP_sha384(); break; #endif #ifdef HAVE_EVP_SHA512 case GETDNS_HMAC_SHA512: digester = EVP_sha512(); break; #endif default : return req->response - req->query; } (void) HMAC(digester, upstream->tsig_key, upstream->tsig_size, (void *)req->query, gldns_buffer_current(&gbuf) - req->query, md_buf, &md_len); gldns_buffer_rewind(&gbuf); gldns_buffer_write(&gbuf, upstream->tsig_dname, upstream->tsig_dname_len); /* Name */ gldns_buffer_write_u16(&gbuf, GETDNS_RRTYPE_TSIG); /* Type*/ gldns_buffer_write_u16(&gbuf, GETDNS_RRCLASS_ANY); /* Class */ gldns_buffer_write_u32(&gbuf, 0); /* TTL */ gldns_buffer_write_u16(&gbuf, (uint16_t)(tsig_info->dname_len + 10 + md_len + 6)); /* RdLen */ gldns_buffer_write(&gbuf, tsig_info->dname, tsig_info->dname_len); /* Algorithm Name */ gldns_buffer_write_u48(&gbuf, time(NULL)); /* Time Signed */ gldns_buffer_write_u16(&gbuf, 300); /* Fudge */ gldns_buffer_write_u16(&gbuf, md_len); /* MAC Size */ gldns_buffer_write(&gbuf, md_buf, md_len); /* MAC*/ gldns_buffer_write(&gbuf, req->query, 2); /* Original ID */ gldns_buffer_write_u16(&gbuf, 0); /* Error */ gldns_buffer_write_u16(&gbuf, 0); /* Other len */ if (gldns_buffer_position(&gbuf) > gldns_buffer_limit(&gbuf)) return req->response - req->query; DEBUG_STUB("Sending with TSIG, mac length: %d\n", (int)md_len); req->tsig_status = GETDNS_DNSSEC_INSECURE; gldns_write_uint16(req->query + 10, arcount + 1); req->response = gldns_buffer_current(&gbuf); return req->response - req->query; } void _getdns_network_validate_tsig(getdns_network_req *req) { #if defined(HAVE_NSS) || defined(HAVE_NETTLE) (void)req; #else _getdns_rr_iter rr_spc, *rr; _getdns_rdf_iter rdf_spc, *rdf; const uint8_t *request_mac; uint16_t request_mac_len; uint8_t tsig_vars[MAXIMUM_TSIG_SPACE]; gldns_buffer gbuf; const uint8_t *dname; size_t dname_len; const uint8_t *response_mac; uint16_t response_mac_len; uint8_t other_len; uint8_t result_mac[EVP_MAX_MD_SIZE]; unsigned int result_mac_len = EVP_MAX_MD_SIZE; uint16_t original_id; const EVP_MD *digester; HMAC_CTX *ctx; #ifndef HAVE_HMAC_CTX_NEW HMAC_CTX ctx_space; #endif DEBUG_STUB("%s %-35s: Validate TSIG\n", STUB_DEBUG_TSIG, __FUNC__); for ( rr = _getdns_rr_iter_init(&rr_spc, req->query, (req->response - req->query)) ; rr ; rr = _getdns_rr_iter_next(rr)) { if (_getdns_rr_iter_section(rr) == SECTION_ADDITIONAL && gldns_read_uint16(rr->rr_type) == GETDNS_RRTYPE_TSIG) break; } if (!rr || !(rdf = _getdns_rdf_iter_init_at(&rdf_spc, rr, 3))) return; /* No good TSIG sent, so nothing expected on reply */ request_mac_len = gldns_read_uint16(rdf->pos); if (request_mac_len != rdf->nxt - rdf->pos - 2) return; DEBUG_STUB("%s %-35s: Request MAC found length %d\n", STUB_DEBUG_TSIG, __FUNC__, (int)(request_mac_len)); request_mac = rdf->pos + 2; /* Now we expect a TSIG on the response! */ req->tsig_status = GETDNS_DNSSEC_BOGUS; for ( rr = _getdns_rr_iter_init( &rr_spc, req->response, req->response_len) ; rr ; rr = _getdns_rr_iter_next(rr)) { if (_getdns_rr_iter_section(rr) == SECTION_ADDITIONAL && gldns_read_uint16(rr->rr_type) == GETDNS_RRTYPE_TSIG) break; } if (!rr || !(rdf = _getdns_rdf_iter_init(&rdf_spc, rr))) return; gldns_buffer_init_frm_data(&gbuf, tsig_vars, MAXIMUM_TSIG_SPACE); dname_len = gldns_buffer_remaining(&gbuf); if (!(dname = _getdns_owner_if_or_as_decompressed( rr, gldns_buffer_current(&gbuf), &dname_len))) return; if (dname == gldns_buffer_current(&gbuf)) gldns_buffer_skip(&gbuf, dname_len); else gldns_buffer_write(&gbuf, dname, dname_len); gldns_buffer_write(&gbuf, rr->rr_type + 2, 2); /* Class */ gldns_buffer_write(&gbuf, rr->rr_type + 4, 4); /* TTL */ dname_len = gldns_buffer_remaining(&gbuf); if (!(dname = _getdns_rdf_if_or_as_decompressed( rdf, gldns_buffer_current(&gbuf), &dname_len))) return; if (dname == gldns_buffer_current(&gbuf)) gldns_buffer_skip(&gbuf, dname_len); else gldns_buffer_write(&gbuf, dname, dname_len); if (!(rdf = _getdns_rdf_iter_next(rdf)) || rdf->nxt - rdf->pos != 6) return; gldns_buffer_write(&gbuf, rdf->pos, 6); /* Time Signed */ if (!(rdf = _getdns_rdf_iter_next(rdf)) || rdf->nxt - rdf->pos != 2) return; gldns_buffer_write(&gbuf, rdf->pos, 2); /* Fudge */ if (!(rdf = _getdns_rdf_iter_next(rdf))) /* mac */ return; response_mac_len = gldns_read_uint16(rdf->pos); if (response_mac_len != rdf->nxt - rdf->pos - 2) return; DEBUG_STUB("%s %-35s: Response MAC found length: %d\n", STUB_DEBUG_TSIG, __FUNC__, (int)(response_mac_len)); response_mac = rdf->pos + 2; if (!(rdf = _getdns_rdf_iter_next(rdf)) || rdf->nxt -rdf->pos != 2) /* Original ID */ return; original_id = gldns_read_uint16(rdf->pos); if (!(rdf = _getdns_rdf_iter_next(rdf)) || rdf->nxt - rdf->pos != 2) return; gldns_buffer_write(&gbuf, rdf->pos, 2); /* Error */ if (!(rdf = _getdns_rdf_iter_next(rdf))) /* Other */ return; gldns_buffer_write_u16(&gbuf, 0); /* Other len */ other_len = (uint8_t) gldns_read_uint16(rdf->pos); if (other_len != rdf->nxt - rdf->pos - 2) return; if (other_len) gldns_buffer_write(&gbuf, rdf->pos, other_len); /* TSIG found */ DEBUG_STUB("%s %-35s: TSIG found, original ID: %d\n", STUB_DEBUG_TSIG, __FUNC__, (int)original_id); gldns_write_uint16(req->response + 10, gldns_read_uint16(req->response + 10) - 1); gldns_write_uint16(req->response, original_id); switch (req->upstream->tsig_alg) { #ifdef HAVE_EVP_MD5 case GETDNS_HMAC_MD5 : digester = EVP_md5() ; break; #endif #ifdef HAVE_EVP_SHA1 case GETDNS_HMAC_SHA1 : digester = EVP_sha1() ; break; #endif #ifdef HAVE_EVP_SHA224 case GETDNS_HMAC_SHA224: digester = EVP_sha224(); break; #endif #ifdef HAVE_EVP_SHA256 case GETDNS_HMAC_SHA256: digester = EVP_sha256(); break; #endif #ifdef HAVE_EVP_SHA384 case GETDNS_HMAC_SHA384: digester = EVP_sha384(); break; #endif #ifdef HAVE_EVP_SHA512 case GETDNS_HMAC_SHA512: digester = EVP_sha512(); break; #endif default : return; } #ifdef HAVE_HMAC_CTX_NEW ctx = HMAC_CTX_new(); #else ctx = &ctx_space; HMAC_CTX_init(ctx); #endif (void) HMAC_Init_ex(ctx, req->upstream->tsig_key, req->upstream->tsig_size, digester, NULL); (void) HMAC_Update(ctx, request_mac - 2, request_mac_len + 2); (void) HMAC_Update(ctx, req->response, rr->pos - req->response); (void) HMAC_Update(ctx, tsig_vars, gldns_buffer_position(&gbuf)); HMAC_Final(ctx, result_mac, &result_mac_len); DEBUG_STUB("%s %-35s: Result MAC length: %d\n", STUB_DEBUG_TSIG, __FUNC__, (int)(result_mac_len)); if (result_mac_len == response_mac_len && memcmp(result_mac, response_mac, result_mac_len) == 0) req->tsig_status = GETDNS_DNSSEC_SECURE; #ifdef HAVE_HMAC_CTX_FREE HMAC_CTX_free(ctx); #else HMAC_CTX_cleanup(ctx); #endif gldns_write_uint16(req->response, gldns_read_uint16(req->query)); gldns_write_uint16(req->response + 10, gldns_read_uint16(req->response + 10) + 1); #endif } void _getdns_dns_req_free(getdns_dns_req * req) { getdns_network_req **net_req; if (!req) { return; } _getdns_upstreams_dereference(req->upstreams); /* cleanup network requests */ for (net_req = req->netreqs; *net_req; net_req++) network_req_cleanup(*net_req); /* clear timeout event */ if (req->loop && req->loop->vmt && req->timeout.timeout_cb) { req->loop->vmt->clear(req->loop, &req->timeout); req->timeout.timeout_cb = NULL; } if (req->freed) *req->freed = 1; GETDNS_FREE(req->my_mf, req); } static const uint8_t no_suffixes[] = { 1, 0 }; /* create a new dns req to be submitted */ getdns_dns_req * _getdns_dns_req_new(getdns_context *context, getdns_eventloop *loop, const char *name, uint16_t request_type, const getdns_dict *extensions, uint64_t *now_ms) { int dnssec = is_extension_set( extensions, "dnssec", context->dnssec); int dnssec_return_status = is_extension_set( extensions, "dnssec_return_status", context->dnssec_return_status); int dnssec_return_only_secure = is_extension_set( extensions, "dnssec_return_only_secure", context->dnssec_return_only_secure); int dnssec_return_all_statuses = is_extension_set( extensions, "dnssec_return_all_statuses", context->dnssec_return_all_statuses); int dnssec_return_full_validation_chain = is_extension_set( extensions, "dnssec_return_full_validation_chain", context->dnssec_return_full_validation_chain); int dnssec_return_validation_chain = is_extension_set( extensions, "dnssec_return_validation_chain", context->dnssec_return_validation_chain); int edns_cookies = is_extension_set( extensions, "edns_cookies", context->edns_cookies); #ifdef DNSSEC_ROADBLOCK_AVOIDANCE int avoid_dnssec_roadblocks = (extensions == dnssec_ok_checking_disabled_avoid_roadblocks); int dnssec_roadblock_avoidance = avoid_dnssec_roadblocks || (extensions == dnssec_ok_checking_disabled_roadblock_avoidance) || is_extension_set(extensions, "dnssec_roadblock_avoidance", context->dnssec_roadblock_avoidance); #endif int dnssec_extension_set = dnssec || dnssec_return_status || dnssec_return_only_secure || dnssec_return_all_statuses || dnssec_return_validation_chain || dnssec_return_full_validation_chain || (extensions == dnssec_ok_checking_disabled) || (extensions == dnssec_ok_checking_disabled_roadblock_avoidance) || (extensions == dnssec_ok_checking_disabled_avoid_roadblocks) #ifdef DNSSEC_ROADBLOCK_AVOIDANCE || dnssec_roadblock_avoidance #endif ; uint32_t edns_do_bit; int edns_maximum_udp_payload_size; uint32_t get_edns_maximum_udp_payload_size; uint32_t edns_extended_rcode; uint32_t edns_version; getdns_dict *add_opt_parameters; int have_add_opt_parameters; getdns_list *options = NULL; size_t noptions = 0; size_t i; getdns_dict *option; uint32_t option_code; getdns_bindata *option_data; size_t opt_options_size = 0; int with_opt; getdns_dns_req *result = NULL; uint32_t klass = context->specify_class; int a_aaaa_query = is_extension_set(extensions, "return_both_v4_and_v6", context->return_both_v4_and_v6) && ( request_type == GETDNS_RRTYPE_A || request_type == GETDNS_RRTYPE_AAAA ); /* Reserve for the buffer at least one more byte * (to test for udp overflow) (hence the + 1), * And align on the 8 byte boundary (hence the (x + 7) / 8 * 8) */ size_t max_query_sz, max_response_sz, netreq_sz, dnsreq_base_sz; uint8_t *region, *suffixes; int checking_disabled = dnssec_extension_set; int opportunistic = 0; if (extensions == no_dnssec_checking_disabled_opportunistic) { dnssec = 0; dnssec_return_status = 0; dnssec_return_only_secure = 0; dnssec_return_all_statuses = 0; dnssec_return_full_validation_chain = 0; dnssec_return_validation_chain = 0; dnssec_extension_set = 0; #ifdef DNSSEC_ROADBLOCK_AVOIDANCE dnssec_roadblock_avoidance = 0; avoid_dnssec_roadblocks = 0; #endif extensions = NULL; checking_disabled = 1; opportunistic = 1; } else if (extensions == dnssec_ok_checking_disabled || extensions == dnssec_ok_checking_disabled_roadblock_avoidance || extensions == dnssec_ok_checking_disabled_avoid_roadblocks) extensions = NULL; have_add_opt_parameters = getdns_dict_get_dict(extensions, "add_opt_parameters", &add_opt_parameters) == GETDNS_RETURN_GOOD; if (!have_add_opt_parameters && context->add_opt_parameters) { add_opt_parameters = context->add_opt_parameters; have_add_opt_parameters = 1; } if (dnssec_extension_set) { edns_maximum_udp_payload_size = -1; edns_extended_rcode = 0; edns_version = 0; edns_do_bit = 1; } else { edns_maximum_udp_payload_size = context->edns_maximum_udp_payload_size; edns_extended_rcode = context->edns_extended_rcode; edns_version = context->edns_version; edns_do_bit = context->edns_do_bit; if (have_add_opt_parameters) { if (getdns_dict_get_int(add_opt_parameters, "maximum_udp_payload_size", &get_edns_maximum_udp_payload_size)) { if (!getdns_dict_get_int( add_opt_parameters, "udp_payload_size", &get_edns_maximum_udp_payload_size)) edns_maximum_udp_payload_size = get_edns_maximum_udp_payload_size; } else edns_maximum_udp_payload_size = get_edns_maximum_udp_payload_size; (void) getdns_dict_get_int(add_opt_parameters, "extended_rcode", &edns_extended_rcode); (void) getdns_dict_get_int(add_opt_parameters, "version", &edns_version); if (getdns_dict_get_int(add_opt_parameters, "do_bit", &edns_do_bit)) (void) getdns_dict_get_int( add_opt_parameters, "do", &edns_do_bit); } } if (have_add_opt_parameters && getdns_dict_get_list( add_opt_parameters, "options", &options) == GETDNS_RETURN_GOOD) (void) getdns_list_get_length(options, &noptions); with_opt = edns_do_bit != 0 || edns_maximum_udp_payload_size != 512 || edns_extended_rcode != 0 || edns_version != 0 || noptions || edns_cookies || context->edns_client_subnet_private || context->tls_query_padding_blocksize > 1; edns_maximum_udp_payload_size = with_opt && ( edns_maximum_udp_payload_size == -1 || edns_maximum_udp_payload_size > 512 ) ? edns_maximum_udp_payload_size : 512; /* (x + 7) / 8 * 8 to align on 8 byte boundries */ #ifdef DNSSEC_ROADBLOCK_AVOIDANCE if (context->resolution_type == GETDNS_RESOLUTION_RECURSING && (!dnssec_roadblock_avoidance || avoid_dnssec_roadblocks)) #else if (context->resolution_type == GETDNS_RESOLUTION_RECURSING) #endif max_query_sz = 0; else { for (i = 0; i < noptions; i++) { if (getdns_list_get_dict(options, i, &option)) continue; if (getdns_dict_get_int( option, "option_code", &option_code)) continue; if (getdns_dict_get_bindata( option, "option_data", &option_data)) continue; opt_options_size += option_data->size + 2 /* option-code */ + 2 /* option-length */ ; } max_query_sz = ( GLDNS_HEADER_SIZE + 256 + 4 /* dname maximum 255 bytes (256 with mdns)*/ + 12 + opt_options_size /* space needed for OPT (if needed) */ + MAXIMUM_UPSTREAM_OPTION_SPACE + MAXIMUM_TSIG_SPACE + 7) / 8 * 8; } max_response_sz = (( edns_maximum_udp_payload_size != -1 ? edns_maximum_udp_payload_size : 1432 ) + 1 /* +1 for udp overflow detection */ + 7 ) / 8 * 8; netreq_sz = ( sizeof(getdns_network_req) + max_query_sz + max_response_sz + 7 ) / 8 * 8; dnsreq_base_sz = (( sizeof(getdns_dns_req) + (a_aaaa_query ? 3 : 2) * sizeof(getdns_network_req*) + context->suffixes_len ) + 7) / 8 * 8; if (! (region = GETDNS_XMALLOC(context->mf, uint8_t, dnsreq_base_sz + (a_aaaa_query ? 2 : 1) * netreq_sz))) return NULL; (void) memset(region, 0, sizeof(getdns_dns_req)); result = (getdns_dns_req *)region; result->netreqs[0] = (getdns_network_req *)(region + dnsreq_base_sz); if (a_aaaa_query) { result->netreqs[1] = (getdns_network_req *) (region + dnsreq_base_sz + netreq_sz); result->netreqs[2] = NULL; } else result->netreqs[1] = NULL; result->my_mf = context->mf; suffixes = region + dnsreq_base_sz - context->suffixes_len; assert(context->suffixes); assert(context->suffixes_len); memcpy(suffixes, context->suffixes, context->suffixes_len); result->append_name = context->append_name; if (!strlen(name) || name[strlen(name)-1] == '.' || result->append_name == GETDNS_APPEND_NAME_NEVER) { /* Absolute query string, no appending */ result->suffix_len = no_suffixes[0]; result->suffix = no_suffixes + 1; result->suffix_appended = 1; } else { result->suffix_len = suffixes[0]; result->suffix = suffixes + 1; result->suffix_appended = 0; } result->name_len = sizeof(result->name); if (gldns_str2wire_dname_buf(name, result->name, &result->name_len)) { GETDNS_FREE(result->my_mf, result); return NULL; } if (result->append_name == GETDNS_APPEND_NAME_ALWAYS || ( result->append_name == GETDNS_APPEND_NAME_TO_SINGLE_LABEL_FIRST && result->name[0] && result->name[result->name[0]+1] == 0)){ for ( ; result->suffix_len > 1 && *result->suffix ; result->suffix += result->suffix_len , result->suffix_len = *result->suffix++) { if (result->suffix_len + result->name_len - 1 < sizeof(result->name)) { memcpy(result->name + result->name_len - 1, result->suffix, result->suffix_len); result->name_len += result->suffix_len - 1; result->suffix_appended = 1; break; } } } else if (result->append_name == GETDNS_APPEND_NAME_ONLY_TO_SINGLE_LABEL_AFTER_FAILURE && result->name[0] && result->name[result->name[0]+1] != 0) { /* We have multiple labels, no appending */ result->suffix_len = no_suffixes[0]; result->suffix = no_suffixes + 1; result->suffix_appended = 1; } result->context = context; result->loop = loop; result->trans_id = (uint64_t) (intptr_t) result; result->dnssec = dnssec; result->dnssec_return_status = dnssec_return_status; result->dnssec_return_only_secure = dnssec_return_only_secure; result->dnssec_return_all_statuses = dnssec_return_all_statuses; result->dnssec_return_full_validation_chain = dnssec_return_full_validation_chain; result->dnssec_return_validation_chain = dnssec_return_validation_chain || dnssec_return_full_validation_chain; result->dnssec_extension_set = dnssec_extension_set; result->edns_cookies = edns_cookies; #ifdef DNSSEC_ROADBLOCK_AVOIDANCE result->dnssec_roadblock_avoidance = dnssec_roadblock_avoidance; result->avoid_dnssec_roadblocks = avoid_dnssec_roadblocks; #endif result->edns_client_subnet_private = context->edns_client_subnet_private; result->tls_query_padding_blocksize = context->tls_query_padding_blocksize; result->return_call_reporting = is_extension_set(extensions, "return_call_reporting" , context->return_call_reporting); result->add_warning_for_bad_dns = is_extension_set(extensions, "add_warning_for_bad_dns", context->add_warning_for_bad_dns); /* will be set by caller */ result->user_pointer = NULL; result->user_callback = NULL; memset(&result->timeout, 0, sizeof(result->timeout)); /* check the specify_class extension */ (void) getdns_dict_get_int(extensions, "specify_class", &klass); result->request_class = klass; result->upstreams = context->upstreams; if (result->upstreams) result->upstreams->referenced++; result->finished_next = NULL; result->ta_notify = NULL; result->freed = NULL; result->validating = 0; result->waiting_for_ta = 0; result->is_dns_request = 1; result->request_timed_out = 0; result->chain = NULL; network_req_init(result->netreqs[0], result, request_type, checking_disabled, opportunistic, with_opt, edns_maximum_udp_payload_size, edns_extended_rcode, edns_version, edns_do_bit, (uint16_t) opt_options_size, noptions, options, netreq_sz - sizeof(getdns_network_req), max_query_sz, extensions); if (a_aaaa_query) network_req_init(result->netreqs[1], result, ( request_type == GETDNS_RRTYPE_A ? GETDNS_RRTYPE_AAAA : GETDNS_RRTYPE_A ), checking_disabled, opportunistic, with_opt, edns_maximum_udp_payload_size, edns_extended_rcode, edns_version, edns_do_bit, (uint16_t) opt_options_size, noptions, options, netreq_sz - sizeof(getdns_network_req), max_query_sz, extensions); if (*now_ms == 0 && (*now_ms = _getdns_get_now_ms()) == 0) result->expires = 0; else result->expires = *now_ms + context->timeout; return result; } getdns-1.5.1/src/rr-dict.h0000644000175000017500000001342013416117763012240 00000000000000/** * * /brief getdns support functions for DNS Resource Records */ /* * Copyright (c) 2013, NLnet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. */ #ifndef RR_DICT_H_ #define RR_DICT_H_ #include "config.h" #include "getdns/getdns.h" #include "gldns/gbuffer.h" /* rdf_end returns a pointer to the end of this rdf's data, * i.e. where the next rdata field will start. */ typedef const uint8_t *(*_getdns_rdf_end_t)( const uint8_t *pkt, const uint8_t *pkt_end, const uint8_t *rdf); /* Limit checks are already done with _getdns_rdf_end_t */ typedef getdns_return_t (*_getdns_rdf_wire2dict_t)( getdns_dict *dict, const uint8_t *rdf); typedef getdns_return_t (*_getdns_rdf_wire2list_t)( getdns_list *list, const uint8_t *rdf); typedef getdns_return_t (*_getdns_rdf_dict2wire_t)( const getdns_dict *dict, uint8_t *rdata, uint8_t *rdf, size_t *rdf_len); typedef getdns_return_t (*_getdns_rdf_list2wire_t)( const getdns_list *list, size_t index, uint8_t *rdata, uint8_t *rdf, size_t *rdf_len); typedef struct _getdns_rdf_special { _getdns_rdf_end_t rdf_end; _getdns_rdf_wire2dict_t wire2dict; _getdns_rdf_wire2list_t wire2list; _getdns_rdf_dict2wire_t dict2wire; _getdns_rdf_list2wire_t list2wire; } _getdns_rdf_special; /* draft-levine-dnsextlang'ish type rr and rdata definitions */ #define GETDNS_RDF_INTEGER 0x010000 #define GETDNS_RDF_BINDATA 0x020000 #define GETDNS_RDF_DNAME 0x040000 #define GETDNS_RDF_COMPRESSED 0x080000 #define GETDNS_RDF_REPEAT 0x100000 #define GETDNS_RDF_FIXEDSZ 0x0000FF #define GETDNS_RDF_LEN_VAL 0x00FF00 typedef enum _getdns_rdf_wf_type { GETDNS_RDF_N = 0x060000, /* N */ GETDNS_RDF_N_A = 0x060000, /* N[A] */ GETDNS_RDF_N_C = 0x0E0000, /* N[C] */ GETDNS_RDF_N_A_C = 0x0E0000, /* N[A,C] */ GETDNS_RDF_N_M = 0x160000, /* N[M] */ GETDNS_RDF_I1 = 0x010001, /* I1 */ GETDNS_RDF_I2 = 0x010002, /* I2 */ GETDNS_RDF_I4 = 0x010004, /* I4 */ GETDNS_RDF_T = 0x010004, /* T */ /* Time values using ring arithmetics * (rfc1982) for TKEY['inception'], * TKEY['expiration'], * RRSIG['inception'] and * RRSIG['expiration'] */ GETDNS_RDF_T6 = 0x020006, /* T6 */ /* Absolute time values (since epoch) * for TSIG['time_signed'] */ GETDNS_RDF_A = 0x020004, /* A */ GETDNS_RDF_AA = 0x020008, /* AA */ GETDNS_RDF_AAAA = 0x020010, /* AAAA */ GETDNS_RDF_S = 0x020100, /* S */ GETDNS_RDF_S_L = 0x020000, /* S[L] */ GETDNS_RDF_S_M = 0x120100, /* S[M] */ GETDNS_RDF_B = 0x020000, /* B */ GETDNS_RDF_B_C = 0x020100, /* B[C] */ GETDNS_RDF_B32_C = 0x020100, /* B32[C] */ GETDNS_RDF_X = 0x020000, /* X */ GETDNS_RDF_X_C = 0x020100, /* X[C] */ /* for NSEC3['salt'] and * NSEC3PARAM['salt']. */ GETDNS_RDF_X_S = 0x020200, /* X[S] */ /* for OPT['option_data'], * TKEY['key_data'], * TKEY['other_data'], * TSIG['mac'] and * TSIG['other_data'] * Although those do not have an * official presentation format. */ GETDNS_RDF_X6 = 0x020006, GETDNS_RDF_X8 = 0x020008, GETDNS_RDF_R = 0x100000, /* Repeat */ GETDNS_RDF_SPECIAL = 0x800000, } _getdns_rdf_type; typedef struct _getdns_rdata_def { const char *name; _getdns_rdf_type type; _getdns_rdf_special *special; } _getdns_rdata_def; typedef struct _getdns_rr_def { const char *name; const _getdns_rdata_def *rdata; size_t n_rdata_fields; } _getdns_rr_def; const _getdns_rr_def *_getdns_rr_def_lookup(uint16_t rr_type); getdns_return_t _getdns_rr_dict2wire( const getdns_dict *rr_dict, gldns_buffer *buf); const char *_getdns_rr_type_name(int rr_type); #endif /* rrs.h */ getdns-1.5.1/src/tools/0000755000175000017500000000000013416117763011743 500000000000000getdns-1.5.1/src/tools/Makefile.in0000644000175000017500000001114213416117763013727 00000000000000# # @configure_input@ # # Copyright (c) 2013, Verisign, Inc., NLNet Labs # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the names of the copyright holders nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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. package = @PACKAGE_NAME@ version = @PACKAGE_VERSION@ tarname = @PACKAGE_TARNAME@ distdir = $(tarname)-$(version) prefix = @prefix@ exec_prefix = @exec_prefix@ bindir = @bindir@ INSTALL = @INSTALL@ LIBTOOL = ../../libtool srcdir = @srcdir@ CC=@CC@ WPEDANTICFLAG=@WPEDANTICFLAG@ CFLAGS=-I$(srcdir)/.. -I$(srcdir) -I.. $(cflags) @CFLAGS@ @CPPFLAGS@ $(WPEDANTICFLAG) $(XTRA_CFLAGS) LDFLAGS=-L.. @LDFLAGS@ LDLIBS=../libgetdns.la @LIBS@ ALL_OBJS=getdns_query.lo getdns_server_mon.lo PROGRAMS=getdns_query getdns_server_mon .SUFFIXES: .c .o .a .lo .h .c.o: $(CC) $(CFLAGS) -c $< -o $@ .c.lo: $(LIBTOOL) --quiet --tag=CC --mode=compile $(CC) $(CFLAGS) -c $< -o $@ default: all all: $(PROGRAMS) $(ALL_OBJS): $(LIBTOOL) --quiet --tag=CC --mode=compile $(CC) $(CFLAGS) -c $(srcdir)/$(@:.lo=.c) -o $@ getdns_query: getdns_query.lo $(LIBTOOL) --tag=CC --mode=link $(CC) $(CFLAGS) -o $@ getdns_query.lo $(LDFLAGS) $(LDLIBS) getdns_server_mon: getdns_server_mon.lo $(LIBTOOL) --tag=CC --mode=link $(CC) $(CFLAGS) -o $@ getdns_server_mon.lo $(LDFLAGS) $(LDLIBS) stubby: cd .. && $(MAKE) $@ install-getdns_query: getdns_query $(INSTALL) -m 755 -d $(DESTDIR)$(bindir) $(LIBTOOL) --mode=install cp getdns_query $(DESTDIR)$(bindir) uninstall-getdns_query: $(LIBTOOL) --mode=uninstall rm -f $(DESTDIR)$(bindir)/getdns_query install-getdns_server_mon: getdns_server_mon $(INSTALL) -m 755 -d $(DESTDIR)$(bindir) $(LIBTOOL) --mode=install cp getdns_server_mon $(DESTDIR)$(bindir) uninstall-getdns_server_mon: $(LIBTOOL) --mode=uninstall rm -f $(DESTDIR)$(bindir)/getdns_server_mon install-stubby: cd .. && $(MAKE) $@ uninstall-stubby: cd .. && $(MAKE) $@ clean: rm -f *.o *.lo $(PROGRAMS) rm -rf .libs distclean : clean rm -f Makefile Makefile: $(srcdir)/Makefile.in ../../config.status cd ../.. && ./config.status src/test/Makefile depend: (cd $(srcdir) ; awk 'BEGIN{P=1}{if(P)print}/^# Dependencies/{P=0}' Makefile.in > Makefile.in.new ) (blddir=`pwd`; cd $(srcdir) ; gcc -MM -I. -I.. -I"$$blddir"/.. *.c | \ sed -e "s? $$blddir/? ?g" \ -e 's? \([a-z0-9_-]*\)\.\([ch]\)? $$(srcdir)/\1.\2?g' \ -e 's? \.\./\([a-z0-9_-]*\)\.h? $$(srcdir)/../\1.h?g' \ -e 's? \.\./\([a-z0-9_-]*\)/\([a-z0-9_-]*\)\.h? $$(srcdir)/../\1/\2.h?g' \ -e 's? \$$(srcdir)/config\.h? ../config.h?g' \ -e 's? \$$(srcdir)/\.\./config\.h? ../config.h?g' \ -e 's? \$$(srcdir)/\.\./getdns/getdns\.h? ../getdns/getdns.h?g' \ -e 's? \$$(srcdir)/\.\./getdns/getdns_extra\.h? ../getdns/getdns_extra.h?g' \ -e 's!\(.*\)\.o[ :]*!\1.lo \1.o: !g' >> Makefile.in.new ) (cd $(srcdir) ; diff Makefile.in.new Makefile.in && rm Makefile.in.new \ || mv Makefile.in.new Makefile.in ) .PHONY: clean test # Dependencies for getdns_query getdns_query.lo getdns_query.o: $(srcdir)/getdns_query.c \ ../config.h \ $(srcdir)/../debug.h \ ../getdns/getdns.h \ ../getdns/getdns_extra.h # Dependencies for getdns_server_mon getdns_server_mon.lo getdns_server_mon.o: $(srcdir)/getdns_server_mon.c \ ../config.h \ $(srcdir)/../debug.h \ ../getdns/getdns.h \ ../getdns/getdns_extra.h getdns-1.5.1/src/tools/getdns_server_mon.c0000644000175000017500000022037113416117763015557 00000000000000/* * Copyright (c) 2018, NLNet Labs, Sinodun * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 "config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define APP_NAME "getdns_server_mon" #define RTT_CRITICAL_MS 500 #define RTT_WARNING_MS 250 #define CERT_EXPIRY_CRITICAL_DAYS 7 #define CERT_EXPIRY_WARNING_DAYS 14 #define DEFAULT_LOOKUP_NAME "getdnsapi.net" #define DEFAULT_LOOKUP_TYPE GETDNS_RRTYPE_AAAA #define EDNS0_PADDING_CODE 12 static const char TLS13_CIPHER_SUITE[] = "TLS13-AES-256-GCM-SHA384:" "TLS13-CHACHA20-POLY1305-SHA256:" "TLS13-AES-128-GCM-SHA256:" "TLS13-AES-128-CCM-8-SHA256:" "TLS13-AES-128-CCM-SHA256"; #define EXAMPLE_PIN "pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\"" /* Plugin exit values */ typedef enum { EXIT_OK = 0, EXIT_WARNING, EXIT_CRITICAL, EXIT_UNKNOWN, EXIT_USAGE /* Special case - internal only. */ } exit_value; /* Plugin verbosity values */ typedef enum { VERBOSITY_MINIMAL = 0, VERBOSITY_ADDITIONAL, VERBOSITY_CONFIG, VERBOSITY_DEBUG } plugin_verbosity; #define MAX_BASE_OUTPUT_LEN 256 #define MAX_PERF_OUTPUT_LEN 256 static struct test_info_s { getdns_context *context; /* Output */ bool monitoring; FILE *errout; plugin_verbosity verbosity; bool debug_output; char base_output[MAX_BASE_OUTPUT_LEN + 1]; char perf_output[MAX_PERF_OUTPUT_LEN + 1]; /* Test config info */ bool fail_on_dns_errors; } test_info; static void snprintcat(char *buf, size_t buflen, const char *format, ...) { va_list ap; int l = strlen(buf); buf += l; buflen -= l; va_start(ap, format); vsnprintf(buf, buflen, format, ap); va_end(ap); buf[buflen] = '\0'; } static int get_rrtype(const char *t) { char buf[128] = "GETDNS_RRTYPE_"; uint32_t rrtype; long int l; size_t i; char *endptr; if (strlen(t) > sizeof(buf) - 15) return -1; for (i = 14; *t && i < sizeof(buf) - 1; i++, t++) buf[i] = *t == '-' ? '_' : toupper(*t); buf[i] = '\0'; if (!getdns_str2int(buf, &rrtype)) return (int)rrtype; if (strncasecmp(buf + 14, "TYPE", 4) == 0) { l = strtol(buf + 18, &endptr, 10); if (!*endptr && l >= 0 && l < 65536) return l; } return -1; } static const char *getdns_intval_text(int val, const char *name, const char *prefix) { getdns_dict *d = getdns_dict_create(); char buf[128]; static char res[20]; if (getdns_dict_set_int(d, name, val) != GETDNS_RETURN_GOOD) goto err; getdns_pretty_snprint_dict(buf, sizeof(buf), d); const char *p = strstr(buf, prefix); if (!p) goto err; p += strlen(prefix); char *q = res; while (*p && *p != '\n') *q++ = *p++; getdns_dict_destroy(d); return res; err: getdns_dict_destroy(d); snprintf(res, sizeof(res), "%d", val); return res; } static const char *rrtype_text(int rrtype) { return getdns_intval_text(rrtype, "type", "GETDNS_RRTYPE_"); } static const char *rcode_text(int rcode) { return getdns_intval_text(rcode, "rcode", "GETDNS_RCODE_"); } #if OPENSSL_VERSION_NUMBER < 0x10002000 || defined(LIBRESSL_VERSION_NUMBER) /* * Convert date to Julian day. * See https://en.wikipedia.org/wiki/Julian_day */ static long julian_day(const struct tm *tm) { long dd, mm, yyyy; dd = tm->tm_mday; mm = tm->tm_mon + 1; yyyy = tm->tm_year + 1900; return (1461 * (yyyy + 4800 + (mm - 14) / 12)) / 4 + (367 * (mm - 2 - 12 * ((mm - 14) / 12))) / 12 - (3 * ((yyyy + 4900 + (mm - 14) / 12) / 100)) / 4 + dd - 32075; } static long secs_in_day(const struct tm *tm) { return ((tm->tm_hour * 60) + tm->tm_min) * 60 + tm->tm_sec; } #endif /* * Thanks to: * https://zakird.com/2013/10/13/certificate-parsing-with-openssl */ static bool extract_cert_expiry(const unsigned char *data, size_t len, time_t *t) { X509 *cert = d2i_X509(NULL, &data, len); if (!cert) return false; int day_diff, sec_diff; const long SECS_IN_DAY = 60 * 60 * 24; #if defined(X509_get_notAfter) || defined(HAVE_X509_GET_NOTAFTER) const ASN1_TIME *not_after = X509_get_notAfter(cert); #elif defined(X509_get0_notAfter) || defined(HAVE_X509_GET0_NOTAFTER) const ASN1_TIME *not_after = X509_get0_notAfter(cert); #endif *t = time(NULL); #if OPENSSL_VERSION_NUMBER < 0x10002000 || defined(LIBRESSL_VERSION_NUMBER) /* * OpenSSL before 1.0.2 does not support ASN1_TIME_diff(). * So work around by using ASN1_TIME_print() to print to a buffer * and parsing that. This does not do any kind of sane format, * but 'Mar 15 11:58:50 2018 GMT'. Note the month name is not * locale-dependent but always English, so strptime() to parse * isn't going to work. It also *appears* to always end 'GMT'. * Ideally one could then convert this UTC time to a time_t, but * there's no way to do that in standard C/POSIX. So follow the * lead of OpenSSL, convert to Julian days and use the difference. */ char buf[40]; BIO *b = BIO_new(BIO_s_mem()); if (ASN1_TIME_print(b, not_after) <= 0) { BIO_free(b); X509_free(cert); return false; } if (BIO_gets(b, buf, sizeof(buf)) <= 0) { BIO_free(b); X509_free(cert); return false; } BIO_free(b); X509_free(cert); struct tm tm; char month[4]; char tz[4]; memset(&tm, 0, sizeof(tm)); if (sscanf(buf, "%3s %d %d:%d:%d %d %3s", month, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &tm.tm_year, tz) != 7) return false; tm.tm_year -= 1900; if (strcmp(tz, "GMT") != 0) return false; const char *mon[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; while(tm.tm_mon < 12 && strcmp(mon[tm.tm_mon], month) != 0) ++tm.tm_mon; if (tm.tm_mon > 11) return false; struct tm tm_now; gmtime_r(t, &tm_now); day_diff = julian_day(&tm) - julian_day(&tm_now); sec_diff = secs_in_day(&tm) - secs_in_day(&tm_now); if (sec_diff < 0) { sec_diff += SECS_IN_DAY; --day_diff; } #else /* * Use ASN1_TIME_diff to get a time delta between now and expiry. * This is much easier than trying to parse the time. */ ASN1_TIME_diff(&day_diff, &sec_diff, NULL, not_after); X509_free(cert); #endif *t += day_diff * SECS_IN_DAY + sec_diff; return true; } static void exit_tidy() { if (test_info.context) getdns_context_destroy(test_info.context); } static void usage() { fputs( "Usage: " APP_NAME " [-M] [-E] [(-u|-t|-T)] [-S] [-K ]\n" " [-v [-v [-v]]] [-V] @upstream testname []\n" " -M|--monitoring Make output suitable for monitoring tools\n" " -E|--fail-on-dns-errors Fail on DNS error (NXDOMAIN, SERVFAIL)\n" " -u|--udp Use UDP transport\n" " -t|--tcp Use TCP transport\n" " -T|--tls Use TLS transport\n" " -S|--strict-usage-profile Use strict profile (require authentication)\n" " -K|--spki-pin SPKI pin for TLS connections (can repeat)\n" " -v|--verbose Increase output verbosity\n" " -D|--debug Enable debugging output\n" " -V|--version Report GetDNS version\n" "\n" "spki-pin: Should look like '" EXAMPLE_PIN "'\n" "\n" "upstream: @[%][#][~tls name>][^]\n" " @ may be given as : or\n" " '['[%]']':\n" "\n" "tsig spec: [:]:\n" "\n" "Tests:\n" " lookup [ []] Check lookup on server\n" " keepalive [ []] Check server support for EDNS0 keepalive in\n" " TCP or TLS connections\n" " Timeout of 0 is off.\n" " OOOR Check whether server delivers responses out of\n" " query order on a TCP or TLS connection\n" " qname-min Check whether server supports QNAME minimisation\n" " rtt [warn-ms,crit-ms] [ []]\n" " Check if server round trip time exceeds\n" " thresholds (default 250,500)\n" "\n" " dnssec-validate Check whether server does DNSSEC validation\n" "\n" " tls-auth [ []] Check authentication of TLS server\n" " If both a SPKI pin and authentication name are\n" " provided, both must authenticate for this test\n" " to pass.\n" " tls-cert-valid [warn-days,crit-days] [ [type]]\n" " Check server certificate validity, report\n" " warning or critical if days to expiry at\n" " or below thresholds (default 14,7).\n" " tls-padding [ []]\n" " Check server support for EDNS0 padding in TLS\n" " Special blocksize values are 0 = off,\n" " 1 = sensible default.\n" " tls-1.3 Check whether server supports TLS 1.3\n" "\n" "Enabling monitoring mode ensures output messages and exit statuses conform\n" "to the requirements of monitoring plugins (www.monitoring-plugins.org).\n", test_info.errout); exit(EXIT_UNKNOWN); } static void version() { fprintf(test_info.errout, APP_NAME ": getdns version %s, API version '%s'.\n", getdns_get_version(), getdns_get_api_version()); exit(EXIT_UNKNOWN); } /** ** Functions used by tests. **/ static void get_thresholds(char ***av, int *critical, int *warning) { if (**av) { char *comma = strchr(**av, ','); if (!comma) return; char *end; long w,c; w = strtol(**av, &end, 10); /* * If the number doesn't end at a comma, this isn't a * properly formatted thresholds arg. Pass over it. */ if (end != comma) return; /* * Similarly, if the number doesn't end at the end of the * argument, this isn't a properly formatted arg. */ c = strtol(comma + 1, &end, 10); if (*end != '\0') return; /* Got two numbers, so consume the argument. */ *critical = (int) c; *warning = (int) w; ++*av; return; } return; } static exit_value get_name_type_args(struct test_info_s *test_info, char ***av, const char **lookup_name, uint32_t *lookup_type) { if (**av) { if (strlen(**av) > 0) { *lookup_name = **av; } else { strcpy(test_info->base_output, "Empty name not valid"); return EXIT_UNKNOWN; } ++*av; if (**av) { int rrtype = get_rrtype(**av); if (rrtype >= 0) { *lookup_type = (uint32_t) rrtype; ++*av; } } } return EXIT_OK; } static exit_value search(struct test_info_s *test_info, const char *name, uint16_t type, getdns_dict *extensions, getdns_dict **response, getdns_return_t *getdns_return) { getdns_return_t ret; getdns_dict *search_extensions = (extensions) ? extensions : getdns_dict_create(); /* We always turn on the return_call_reporting extension. */ if ((ret = getdns_dict_set_int(search_extensions, "return_call_reporting", GETDNS_EXTENSION_TRUE)) != GETDNS_RETURN_GOOD) { if (getdns_return) *getdns_return = ret; snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot set return call reporting: %s (%d)", getdns_get_errorstr_by_id(ret), ret); if (!extensions) getdns_dict_destroy(search_extensions); return EXIT_UNKNOWN; } if (test_info->verbosity >= VERBOSITY_ADDITIONAL && !test_info->monitoring) { printf("DNS Lookup name:\t%s\n", name); printf("DNS Lookup RR type:\t%s\n", rrtype_text(type)); } if (test_info->debug_output) { printf("Context: %s\n", getdns_pretty_print_dict(getdns_context_get_api_information(test_info->context))); } ret = getdns_general_sync(test_info->context, name, type, search_extensions, response); if (!extensions) getdns_dict_destroy(search_extensions); if (ret != GETDNS_RETURN_GOOD) { if (getdns_return) { *getdns_return = ret; } else { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Error resolving '%s': %s (%d)", name, getdns_get_errorstr_by_id(ret), ret); } return EXIT_CRITICAL; } if (test_info->debug_output) { printf("Response: %s\n", getdns_pretty_print_dict(*response)); } if (getdns_return) *getdns_return = ret; return EXIT_OK; } static exit_value get_result(struct test_info_s *test_info, const getdns_dict *response, uint32_t *error_id, uint32_t *rcode) { getdns_return_t ret; if ((ret = getdns_dict_get_int(response, "status", error_id)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get result status: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (*error_id != GETDNS_RESPSTATUS_GOOD && *error_id != GETDNS_RESPSTATUS_NO_NAME) { *rcode = 0; return EXIT_OK; } if ((ret = getdns_dict_get_int(response, "/replies_tree/0/header/rcode", rcode)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get DNS return code: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } return EXIT_OK; } static exit_value check_result(struct test_info_s *test_info, const getdns_dict *response) { exit_value xit; uint32_t error_id, rcode; if ((xit = get_result(test_info, response, &error_id, &rcode)) != EXIT_OK) return xit; switch(error_id) { case GETDNS_RESPSTATUS_ALL_TIMEOUT: strcpy(test_info->base_output, "Search timed out"); return EXIT_CRITICAL; case GETDNS_RESPSTATUS_NO_SECURE_ANSWERS: strcpy(test_info->base_output, "No secure answers"); return EXIT_CRITICAL; case GETDNS_RESPSTATUS_ALL_BOGUS_ANSWERS: strcpy(test_info->base_output, "All answers are bogus"); return EXIT_CRITICAL; default: break; } if (test_info->verbosity >= VERBOSITY_ADDITIONAL){ if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "getdns=%d;", error_id); } else { printf("getdns result:\t\t%s (%d)\n", getdns_get_errorstr_by_id(error_id), error_id); } } if (test_info->fail_on_dns_errors && rcode > 0) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "DNS error %s (%d)", rcode_text(rcode), rcode); return EXIT_CRITICAL; } return EXIT_OK; } static exit_value get_report_info(struct test_info_s *test_info, const getdns_dict *response, uint32_t *rtt, getdns_bindata **auth_status, time_t *cert_expire_time) { getdns_return_t ret; getdns_list *l; uint32_t rtt_val; getdns_bindata *auth_status_val = NULL; time_t cert_expire_time_val = 0; if ((ret = getdns_dict_get_list(response, "call_reporting", &l)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get call report: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } getdns_dict *d; if ((ret = getdns_list_get_dict(l, 0, &d)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get call report first item: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (test_info->verbosity >= VERBOSITY_ADDITIONAL) { uint32_t transport; const char *transport_text = "???"; if ((ret = getdns_dict_get_int(d, "transport", &transport)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get transport: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } switch(transport) { case GETDNS_TRANSPORT_UDP: transport_text = "UDP"; break; case GETDNS_TRANSPORT_TCP: transport_text = "TCP"; break; case GETDNS_TRANSPORT_TLS: transport_text = "TLS"; break; } if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "transport=%s;", transport_text); } else { printf("Transport:\t\t%s\n", transport_text); } } if ((ret = getdns_dict_get_int(d, "run_time/ms", &rtt_val)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get RTT: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (rtt) *rtt = rtt_val; if (test_info->verbosity >= VERBOSITY_ADDITIONAL) { if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "rtt=%dms;", rtt_val); } else { printf("RTT:\t\t\t%dms\n", rtt_val); } } if (getdns_dict_get_bindata(d, "tls_auth_status", &auth_status_val) == GETDNS_RETURN_GOOD) { const char *auth_status_text = (char *) auth_status_val->data; /* Just in case - not sure this is necessary */ auth_status_val->data[auth_status_val->size] = '\0'; if (test_info->verbosity >= VERBOSITY_ADDITIONAL) { if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "auth=%s;", auth_status_text); } else { printf("Authentication:\t\t%s\n", auth_status_text); } } } if (auth_status) *auth_status = auth_status_val; getdns_bindata *cert; if (getdns_dict_get_bindata(d, "tls_peer_cert", &cert) == GETDNS_RETURN_GOOD) { if (!extract_cert_expiry(cert->data, cert->size, &cert_expire_time_val)) { strcpy(test_info->base_output, "Cannot parse PKIX certificate"); return EXIT_UNKNOWN; } if (test_info->verbosity >= VERBOSITY_ADDITIONAL) { struct tm *tm = gmtime(&cert_expire_time_val); char buf[25]; strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm); if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "expire=%s;", buf); } else { printf("Certificate expires:\t%s UTC\n", buf); } } } if (cert_expire_time) *cert_expire_time = cert_expire_time_val; getdns_bindata *tls_version; if (getdns_dict_get_bindata(d, "tls_version", &tls_version) == GETDNS_RETURN_GOOD) { const char *version_text = (char *) tls_version->data; if (test_info->verbosity >= VERBOSITY_ADDITIONAL) { if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "tls=%s;", version_text); } else { printf("TLS version:\t\t%s\n", version_text); } } /* * This is always in the context, so show only if we got * TLS info in the call reporting. */ uint32_t tls_auth; getdns_dict *context_dict = getdns_context_get_api_information(test_info->context); if (getdns_dict_get_int(context_dict, "/all_context/tls_authentication", &tls_auth) == GETDNS_RETURN_GOOD) { const char *auth_text = "???"; switch(tls_auth) { case GETDNS_AUTHENTICATION_NONE: auth_text = "Opportunistic"; break; case GETDNS_AUTHENTICATION_REQUIRED: auth_text = "Strict"; break; } if (test_info->verbosity >= VERBOSITY_ADDITIONAL) { if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "%s;", auth_text); } else { printf("TLS authentication:\t%s\n", auth_text); } } } } return EXIT_OK; } static exit_value get_answers(struct test_info_s *test_info, const getdns_dict *response, const char *section, getdns_list **answers, size_t *no_answers) { getdns_return_t ret; char buf[40]; snprintf(buf, sizeof(buf), "/replies_tree/0/%s", section); if ((ret = getdns_dict_get_list(response, buf, answers)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get section '%s': %s (%d)", section, getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if ((ret = getdns_list_get_length(*answers, no_answers)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get number of items in '%s': %s (%d)", section, getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (*no_answers <= 0) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Zero entries in '%s'", section); return EXIT_WARNING; } return EXIT_OK; } static exit_value check_answer_type(struct test_info_s *test_info, const getdns_dict *response, uint32_t rrtype) { getdns_list *answers; size_t no_answers; exit_value xit; if ((xit = get_answers(test_info, response, "answer", &answers, &no_answers)) != EXIT_OK) return xit; for (size_t i = 0; i < no_answers; ++i) { getdns_dict *answer; getdns_return_t ret; if ((ret = getdns_list_get_dict(answers, i, &answer)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get answer number %zu: %s (%d)", i, getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } uint32_t rtype; if ((ret = getdns_dict_get_int(answer, "type", &rtype)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get answer type: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (rtype == rrtype) return EXIT_OK; } strcpy(test_info->base_output, "Answer does not contain expected type"); return EXIT_UNKNOWN; } static exit_value search_check(struct test_info_s *test_info, const char *lookup_name, uint16_t lookup_type, getdns_dict **response, uint32_t *rtt, getdns_bindata **auth_status, time_t *cert_expire_time) { exit_value xit; getdns_dict *resp; if ((xit = search(test_info, lookup_name, lookup_type, NULL, &resp, NULL)) != EXIT_OK) return xit; if ((xit = check_result(test_info, resp)) != EXIT_OK) return xit; if ((xit = get_report_info(test_info, resp, rtt, auth_status, cert_expire_time)) != EXIT_OK) return xit; if ((xit = check_answer_type(test_info, resp, lookup_type)) != EXIT_OK) return xit; if (response) *response = resp; return xit; } static exit_value parse_search_check(struct test_info_s *test_info, char **av, const char *usage, getdns_dict **response, uint32_t *rtt, getdns_bindata **auth_status, time_t *cert_expire_time) { const char *lookup_name = DEFAULT_LOOKUP_NAME; uint32_t lookup_type = DEFAULT_LOOKUP_TYPE; exit_value xit; if ((xit = get_name_type_args(test_info, &av, &lookup_name, &lookup_type)) != EXIT_OK) return xit; if (*av) { strcpy(test_info->base_output, usage); return EXIT_USAGE; } return search_check(test_info, lookup_name, lookup_type, response, rtt, auth_status, cert_expire_time); } /** ** Test routines. **/ static exit_value test_lookup(struct test_info_s *test_info, char ** av) { exit_value xit; if ((xit = parse_search_check(test_info, av, "lookup takes arguments [ []]", NULL, NULL, NULL, NULL)) != EXIT_OK) return xit; strcpy(test_info->base_output, "Lookup succeeded"); return EXIT_OK; } static exit_value test_rtt(struct test_info_s *test_info, char ** av) { exit_value xit; int critical_ms = RTT_CRITICAL_MS; int warning_ms = RTT_WARNING_MS; uint32_t rtt_val; get_thresholds(&av, &critical_ms, &warning_ms); if ((xit = parse_search_check(test_info, av, "rtt takes arguments [warn-ms,crit-ms] [ []]", NULL, &rtt_val, NULL, NULL)) != EXIT_OK) return xit; snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "RTT lookup succeeded in %dms", rtt_val); if ((int) rtt_val > critical_ms) return EXIT_CRITICAL; else if ((int) rtt_val > warning_ms) return EXIT_WARNING; return EXIT_OK; } static exit_value test_authenticate(struct test_info_s *test_info, char ** av) { exit_value xit; getdns_bindata *auth_status; if ((xit = parse_search_check(test_info, av, "auth takes arguments [ []]", NULL, NULL, &auth_status, NULL)) != EXIT_OK) return xit; if (!auth_status || strcmp((char *) auth_status->data, "Success") != 0) { strcpy(test_info->base_output, "Authentication failed"); return EXIT_CRITICAL; } else { strcpy(test_info->base_output, "Authentication succeeded"); return EXIT_OK; } } static exit_value test_certificate_valid(struct test_info_s *test_info, char **av) { exit_value xit; int warning_days = CERT_EXPIRY_WARNING_DAYS; int critical_days = CERT_EXPIRY_CRITICAL_DAYS; time_t expire_time; get_thresholds(&av, &critical_days, &warning_days); if ((xit = parse_search_check(test_info, av, "cert-valid takes arguments [warn-days,crit-days] [ []]", NULL, NULL, NULL, &expire_time)) != EXIT_OK) return xit; if (expire_time == 0) { strcpy(test_info->base_output, "No PKIX certificate"); return EXIT_CRITICAL; } time_t now = time(NULL); int days_to_expiry = (expire_time - now) / 86400; if (days_to_expiry < 0) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Certificate expired %d day%s ago", -days_to_expiry, (days_to_expiry < -1) ? "s" : ""); return EXIT_CRITICAL; } if (days_to_expiry == 0) { strcpy(test_info->base_output, "Certificate expires today"); } else { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Certificate will expire in %d day%s", days_to_expiry, (days_to_expiry > 1) ? "s" : ""); } if (days_to_expiry <= critical_days) { return EXIT_CRITICAL; } if (days_to_expiry <= warning_days) { return EXIT_WARNING; } return EXIT_OK; } static exit_value test_qname_minimisation(struct test_info_s *test_info, char ** av) { if (*av) { strcpy(test_info->base_output, "qname-min takes no arguments"); return EXIT_USAGE; } getdns_dict *response; exit_value xit; if ((xit = search_check(test_info, "qnamemintest.internet.nl", GETDNS_RRTYPE_TXT, &response, NULL, NULL, NULL)) != EXIT_OK) return xit; getdns_list *answers; size_t no_answers; if ((xit = get_answers(test_info, response, "answer", &answers, &no_answers)) != EXIT_OK) return xit; for (size_t i = 0; i < no_answers; ++i) { getdns_dict *answer; getdns_return_t ret; if ((ret = getdns_list_get_dict(answers, i, &answer)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get answer number %zu: %s (%d)", i, getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } uint32_t rtype; if ((ret = getdns_dict_get_int(answer, "type", &rtype)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get answer type: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (rtype != GETDNS_RRTYPE_TXT) continue; getdns_bindata *rtxt; if ((ret = getdns_dict_get_bindata(answer, "/rdata/txt_strings/0", &rtxt)) != GETDNS_RETURN_GOOD) { strcpy(test_info->base_output, "No answer text"); return EXIT_UNKNOWN; } if (rtxt->size > 0 ) { switch(rtxt->data[0]) { case 'H': strcpy(test_info->base_output, "QNAME minimisation ON"); return EXIT_OK; case 'N': strcpy(test_info->base_output, "QNAME minimisation OFF"); return EXIT_CRITICAL; default: /* Unrecognised message. */ break; } } } strcpy(test_info->base_output, "No valid QNAME minimisation data"); return EXIT_UNKNOWN; } static exit_value test_padding(struct test_info_s *test_info, char ** av) { getdns_dict *response; exit_value xit; long blocksize; char *endptr; const char USAGE[] = "padding takes arguments [ []]"; if (!*av || (blocksize = strtol(*av, &endptr, 10), *endptr != '\0' || blocksize < 0)) { strcpy(test_info->base_output, USAGE); return EXIT_USAGE; } ++av; getdns_return_t ret; if ((ret = getdns_context_set_tls_query_padding_blocksize(test_info->context, (uint16_t) blocksize)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot set padding blocksize: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if ((xit = parse_search_check(test_info, av, USAGE, &response, NULL, NULL, NULL)) != EXIT_OK) return xit; getdns_list *answers; size_t no_answers; if ((xit = get_answers(test_info, response, "additional", &answers, &no_answers)) != EXIT_OK) return xit; for (size_t i = 0; i < no_answers; ++i) { getdns_dict *answer; getdns_return_t ret; if ((ret = getdns_list_get_dict(answers, i, &answer)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get answer number %zu: %s (%d)", i, getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } uint32_t rtype; if ((ret = getdns_dict_get_int(answer, "type", &rtype)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get answer type: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (rtype != GETDNS_RRTYPE_OPT) continue; getdns_list *options; size_t no_options; if ((ret = getdns_dict_get_list(answer, "/rdata/options", &options)) != GETDNS_RETURN_GOOD) { goto no_padding; } if ((ret = getdns_list_get_length(options, &no_options)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get number of options: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } for (size_t j = 0; j < no_options; ++j) { getdns_dict *option; uint32_t code; if ((ret = getdns_list_get_dict(options, j, &option)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get option number %zu: %s (%d)", j, getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if ((ret = getdns_dict_get_int(option, "option_code", &code)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get option code: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (code != EDNS0_PADDING_CODE) continue; /* Yes, we have padding! */ getdns_bindata *data; if ((ret = getdns_dict_get_bindata(option, "option_data", &data)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get option code: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Padding found, length %zu", data->size); return EXIT_OK; } } no_padding: strcpy(test_info->base_output, "No padding found"); return EXIT_CRITICAL; } static exit_value test_keepalive(struct test_info_s *test_info, char ** av) { getdns_dict *response; exit_value xit; const uint64_t MAX_TIMEOUT_VALUE = 0xffff * 10000; getdns_return_t ret; if ((ret = getdns_context_set_idle_timeout(test_info->context, MAX_TIMEOUT_VALUE)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot set keepalive timeout: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if ((xit = parse_search_check(test_info, av, "keepalive takes arguments [ []]", &response, NULL, NULL, NULL)) != EXIT_OK) return xit; getdns_list *l; if ((ret = getdns_dict_get_list(response, "call_reporting", &l)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get call report: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } getdns_dict *d; if ((ret = getdns_list_get_dict(l, 0, &d)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get call report first item: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } /* Search is forced to be TCP or TLS, so server keepalive flag must exist. */ uint32_t server_keepalive_received; if ((ret = getdns_dict_get_int(d, "server_keepalive_received", &server_keepalive_received)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get server keepalive flag: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (server_keepalive_received) { uint32_t t; bool overflow = false; if (!((ret = getdns_dict_get_int(d, "idle timeout in ms", &t)) == GETDNS_RETURN_GOOD || (overflow = true, ret = getdns_dict_get_int(d, "idle timeout in ms (overflow)", &t)) == GETDNS_RETURN_GOOD)) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get idle timeout: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } if (overflow) { strcpy(test_info->base_output, "Server sent keepalive, idle timeout now (overflow)"); } else { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Server sent keepalive, idle timeout now %ums", t); } return EXIT_OK; } else { strcpy(test_info->base_output, "Server did not send keepalive"); return EXIT_CRITICAL; } } static exit_value test_dnssec_validate(struct test_info_s *test_info, char ** av) { if (*av) { strcpy(test_info->base_output, "dnssec-validate takes no arguments"); return EXIT_USAGE; } getdns_dict *response; exit_value xit; if ((xit = search(test_info, "dnssec-failed.org", GETDNS_RRTYPE_A, NULL, &response, NULL)) != EXIT_OK) return xit; uint32_t error_id, rcode; if ((xit = get_result(test_info, response, &error_id, &rcode)) != EXIT_OK) return xit; if (error_id == GETDNS_RESPSTATUS_ALL_TIMEOUT) { strcpy(test_info->base_output, "Search timed out"); return EXIT_CRITICAL; } if (rcode != GETDNS_RCODE_SERVFAIL) { strcpy(test_info->base_output, "Server does NOT validate DNSSEC"); return EXIT_CRITICAL; } /* * Rerun the query, but this time set the CD bit. The lookup should * succeed. */ getdns_return_t ret; getdns_dict *response2; getdns_dict *extensions = getdns_dict_create(); if ((ret = getdns_dict_set_int(extensions, "/header/cd", 1)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot set CD bit: %s (%d)", getdns_get_errorstr_by_id(ret), ret); getdns_dict_destroy(extensions); return EXIT_UNKNOWN; } if ((xit = search(test_info, "dnssec-failed.org", GETDNS_RRTYPE_A, extensions, &response2, NULL)) != EXIT_OK) return xit; getdns_dict_destroy(extensions); /* * Only now get report info from the first search, so that any * verbose output appears after the context/response dumps. */ if ((xit = get_report_info(test_info, response, NULL, NULL, NULL)) != EXIT_OK) return xit; if ((xit = get_result(test_info, response2, &error_id, &rcode)) != EXIT_OK) return xit; if (error_id == GETDNS_RESPSTATUS_ALL_TIMEOUT) { strcpy(test_info->base_output, "Search timed out"); return EXIT_CRITICAL; } if (error_id != GETDNS_RESPSTATUS_GOOD || rcode != GETDNS_RCODE_NOERROR) { strcpy(test_info->base_output, "Server error - cannot determine DNSSEC status"); return EXIT_UNKNOWN; } strcpy(test_info->base_output, "Server validates DNSSEC"); return EXIT_OK; } static exit_value test_tls13(struct test_info_s *test_info, char ** av) { exit_value xit; getdns_return_t ret; if (*av) { strcpy(test_info->base_output, "tls-1.3 takes no arguments"); return EXIT_USAGE; } /* * Set cipher list to TLS 1.3-only ciphers. If we are using * an OpenSSL version that doesn't support TLS 1.3 this will cause * a Bad Context error on the lookup. */ if ((ret = getdns_context_set_tls_cipher_list(test_info->context, TLS13_CIPHER_SUITE)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot set TLS 1.3 cipher list: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } getdns_dict *response; if ((xit = search(test_info, DEFAULT_LOOKUP_NAME, DEFAULT_LOOKUP_TYPE, NULL, &response, &ret)) != EXIT_OK) { if (xit == EXIT_CRITICAL) { if (ret == GETDNS_RETURN_BAD_CONTEXT) { strcpy(test_info->base_output, "Your version of OpenSSL does not support TLS 1.3 ciphers. You need at least OpenSSL 1.1.1."); return EXIT_UNKNOWN; } else { strcpy(test_info->base_output, "Cannot establish TLS 1.3 connection."); return EXIT_CRITICAL; } } else { return xit; } } if ((xit = get_report_info(test_info, response, NULL, NULL, NULL)) != EXIT_OK) return xit; getdns_list *l; if ((ret = getdns_dict_get_list(response, "call_reporting", &l)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get call report: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } getdns_dict *d; if ((ret = getdns_list_get_dict(l, 0, &d)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get call report first item: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } /* Search is forced TLS, so tls_version flag must exist. */ getdns_bindata *version; if ((ret = getdns_dict_get_bindata(d, "tls_version", &version)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Cannot get TLS version: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } const char TLS_1_3_SIG[] = "TLSv1.3"; if (strncmp((const char *)version->data, TLS_1_3_SIG, sizeof(TLS_1_3_SIG) - 1) != 0) { strcpy(test_info->base_output, "Server does not support TLS 1.3"); return EXIT_CRITICAL; } if ((xit = check_result(test_info, response)) != EXIT_OK) return xit; strcpy(test_info->base_output, "Server supports TLS 1.3"); return EXIT_OK; } struct async_query { const char *name; unsigned done_order; bool error; }; static void out_of_order_callback(getdns_context *context, getdns_callback_type_t callback_type, getdns_dict *response, void *userarg, getdns_transaction_t transaction_id) { (void) context; (void) callback_type; (void) response; (void) transaction_id; struct async_query *query = (struct async_query *) userarg; static unsigned callback_no; query->done_order = ++callback_no; query->error = (callback_type != GETDNS_CALLBACK_COMPLETE); if (test_info.verbosity >= VERBOSITY_ADDITIONAL) { if (test_info.monitoring) { snprintcat(test_info.perf_output, MAX_PERF_OUTPUT_LEN, "->%s;", query->name); } else { printf("Result:\t\t\t%s", query->name); if (query->error) printf(" (callback %d)\n", callback_type); else putchar('\n'); } } } static exit_value test_out_of_order(struct test_info_s *test_info, char ** av) { if (*av) { strcpy(test_info->base_output, "OOOR takes no arguments"); return EXIT_USAGE; } /* * A set of asynchronous queries to send. One exists. * * Replies from delay.getdns.api come back with a 1s TTL. It turns out * that delay.getdns.api will ignore all leftmost labels bar the first, * so to further mitigate any cache effects insert a random string * into the name. */ const char GOOD_NAME[] = "getdnsapi.net"; char delay_name[50]; srand(time(NULL)); snprintf(delay_name, sizeof(delay_name) - 1, "400.n%04d.delay.getdnsapi.net", rand() % 10000); struct async_query async_queries[] = { { delay_name, 0, false }, { GOOD_NAME, 0, false } }; unsigned NQUERIES = sizeof(async_queries) / sizeof(async_queries[0]); /* Pre-load the cache with result of the good query. */ getdns_dict *response; exit_value xit; if ((xit = search_check(test_info, GOOD_NAME, GETDNS_RRTYPE_AAAA, &response, NULL, NULL, NULL)) != EXIT_OK) return xit; /* Now launch async searches for all the above. */ for (unsigned i = 0; i < NQUERIES; ++i) { getdns_return_t ret; if (test_info->verbosity >= VERBOSITY_ADDITIONAL) { if (test_info->monitoring) { snprintcat(test_info->perf_output, MAX_PERF_OUTPUT_LEN, "%s->;", async_queries[i].name); } else { printf("Search:\t\t\t%s\n", async_queries[i].name); } } if ((ret = getdns_general(test_info->context, async_queries[i].name, GETDNS_RRTYPE_AAAA, NULL, &async_queries[i], NULL, out_of_order_callback)) != GETDNS_RETURN_GOOD) { snprintf(test_info->base_output, MAX_BASE_OUTPUT_LEN, "Async search failed: %s (%d)", getdns_get_errorstr_by_id(ret), ret); return EXIT_UNKNOWN; } } /* And wait for them to complete. */ getdns_context_run(test_info->context); for (unsigned i = 0; i < NQUERIES; ++i) { if (async_queries[i].error) { strcpy(test_info->base_output, "Query did not complete"); return EXIT_UNKNOWN; } } if (async_queries[NQUERIES - 1].done_order == NQUERIES) { strcpy(test_info->base_output, "Responses are in query order"); return EXIT_CRITICAL; } else { strcpy(test_info->base_output, "Responses are not in query order"); return EXIT_OK; } } static struct test_funcs_s { const char *name; bool implies_tls; bool implies_tcp; exit_value (*func)(struct test_info_s *test_info, char **av); } TESTS[] = { { "lookup", false, false, test_lookup }, { "rtt", false, false, test_rtt }, { "qname-min", false, false, test_qname_minimisation }, { "tls-auth", true, false, test_authenticate }, { "tls-cert-valid", true, false, test_certificate_valid }, { "tls-padding", true, false, test_padding }, { "keepalive", false, true, test_keepalive }, { "dnssec-validate", false, false, test_dnssec_validate }, { "tls-1.3", true, false, test_tls13 }, { "OOOR", false, true, test_out_of_order }, { NULL, false, false, NULL } }; int main(int ac, char *av[]) { getdns_return_t ret; getdns_list *pinset = NULL; size_t pinset_size = 0; bool strict_usage_profile = false; bool use_udp = false; bool use_tcp = false; bool use_tls = false; (void) ac; test_info.errout = stderr; atexit(exit_tidy); if ((ret = getdns_context_create(&test_info.context, 1)) != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Create context failed: %s (%d)\n", getdns_get_errorstr_by_id(ret), ret); exit(EXIT_UNKNOWN); } for (++av; *av && *av[0] == '-'; ++av) { if (strcmp(*av, "-M") == 0 || strcmp(*av, "--monitoring") == 0) { test_info.monitoring = true; test_info.errout = stdout; } else if (strcmp(*av, "-D") == 0 || strcmp(*av, "--debug") == 0) { test_info.debug_output = true; } else if (strcmp(*av, "-E") == 0 || strcmp(*av, "--fail-on-dns-errors") == 0) { test_info.fail_on_dns_errors = true; } else if (strcmp(*av, "-u") == 0 || strcmp(*av, "--udp") == 0 ) { use_udp = true; } else if (strcmp(*av, "-t") == 0 || strcmp(*av, "--tcp") == 0 ) { use_tcp = true; } else if (strcmp(*av, "-T") == 0 || strcmp(*av, "--tls") == 0 ) { use_tls = true; } else if (strcmp(*av, "-S") == 0 || strcmp(*av, "--strict-usage-profile") == 0 ) { strict_usage_profile = true; use_tls = true; } else if (strcmp(*av, "-K") == 0 || strcmp(*av, "--spki-pin") == 0 ) { ++av; if (!*av) { fputs("pin string of the form " EXAMPLE_PIN "expected after -K|--pin\n", test_info.errout); exit(EXIT_UNKNOWN); } getdns_dict *pin; pin = getdns_pubkey_pin_create_from_string(test_info.context, *av); if (!pin) { fprintf(test_info.errout, "Could not convert '%s' into a public key pin.\n" "Good pins look like: " EXAMPLE_PIN "\n" "Please see RFC 7469 for details about the format.\n", *av); exit(EXIT_UNKNOWN); } if (!pinset) pinset = getdns_list_create_with_context(test_info.context); ret = getdns_list_set_dict(pinset, pinset_size++, pin); getdns_dict_destroy(pin); if (ret != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Could not add pin '%s' to pin set.\n", *av); getdns_list_destroy(pinset); exit(EXIT_UNKNOWN); } use_tls = true; } else if (strcmp(*av, "-v") == 0 || strcmp(*av, "--verbose") == 0) { ++test_info.verbosity; } else if (strcmp(*av, "-V") == 0 || strcmp(*av, "--version") == 0) { version(); } else { usage(); } } if (*av == NULL || *av[0] != '@') usage(); /* Non-monitoring output is chatty by default. */ if (!test_info.monitoring) ++test_info.verbosity; const char *upstream = *av++; getdns_dict *resolver; getdns_bindata *address; if ((ret = getdns_str2dict(&upstream[1], &resolver)) != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Could not convert \"%s\" to an IP dict: %s (%d)\n", &upstream[1], getdns_get_errorstr_by_id(ret), ret); exit(EXIT_UNKNOWN); } /* If the resolver info include TLS auth name, use TLS. */ getdns_bindata *tls_auth_name; if (getdns_dict_get_bindata(resolver, "tls_auth_name", &tls_auth_name) == GETDNS_RETURN_GOOD) use_tls = true; if ((ret = getdns_dict_get_bindata(resolver, "address_data", &address)) != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "\"%s\" did not translate to an IP dict: %s (%d)\n", &upstream[1], getdns_get_errorstr_by_id(ret), ret); getdns_dict_destroy(resolver); exit(EXIT_UNKNOWN); } /* Set parameters on the resolver. */ if (pinset) { ret = getdns_dict_set_list(resolver, "tls_pubkey_pinset", pinset); getdns_list_destroy(pinset); if (ret != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Cannot set keys for \"%s\": %s (%d)\n", &upstream[1], getdns_get_errorstr_by_id(ret), ret); exit(EXIT_UNKNOWN); } } /* Set getdns context to use the indicated resolver. */ getdns_list *l = getdns_list_create(); ret = getdns_list_set_dict(l, 0, resolver); getdns_dict_destroy(resolver); if (ret != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Unable to add upstream '%s' to list: %s (%d)\n", upstream, getdns_get_errorstr_by_id(ret), ret); getdns_list_destroy(l); exit(EXIT_UNKNOWN); } ret = getdns_context_set_upstream_recursive_servers(test_info.context, l); getdns_list_destroy(l); if (ret != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Unable to set upstream resolver to '%s': %s (%d)\n", upstream, getdns_get_errorstr_by_id(ret), ret); exit(EXIT_UNKNOWN); } /* Set context to stub mode. */ if ((ret = getdns_context_set_resolution_type(test_info.context, GETDNS_RESOLUTION_STUB)) != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Unable to set stub mode: %s (%d)\n", getdns_get_errorstr_by_id(ret), ret); exit(EXIT_UNKNOWN); } /* Set other context parameters. */ if (strict_usage_profile) { ret = getdns_context_set_tls_authentication(test_info.context, GETDNS_AUTHENTICATION_REQUIRED); if (ret != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Unable to set strict profile: %s (%d)\n", getdns_get_errorstr_by_id(ret), ret); exit(EXIT_UNKNOWN); } } /* Choose and run test */ const char *testname = *av; if (!testname) usage(); ++av; const struct test_funcs_s *f; for (f = TESTS; f->name != NULL; ++f) { if (strcmp(testname, f->name) == 0) break; } if (f->name == NULL) { fprintf(test_info.errout, "Unknown test %s\n", testname); exit(EXIT_UNKNOWN); } if (f->implies_tcp) { if (use_udp) { fputs("Test requires TCP or TLS\n", test_info.errout); exit(EXIT_UNKNOWN); } if (!use_tls) use_tcp = true; } if (f->implies_tls) { if (use_udp | use_tcp) { fputs("Test requires TLS, or TLS authentication specified\n", test_info.errout); exit(EXIT_UNKNOWN); } use_tls = true; } if ((use_tls + use_udp + use_tcp) > 1) { fputs("Specify one only of -u, -t, -T\n", test_info.errout); exit(EXIT_UNKNOWN); } if (use_tls || use_udp || use_tcp) { getdns_transport_list_t udp[] = { GETDNS_TRANSPORT_UDP }; getdns_transport_list_t tcp[] = { GETDNS_TRANSPORT_TCP }; getdns_transport_list_t tls[] = { GETDNS_TRANSPORT_TLS }; getdns_transport_list_t *transport = (use_tls) ? tls : (use_tcp) ? tcp : udp; if ((ret = getdns_context_set_dns_transport_list(test_info.context, 1, transport)) != GETDNS_RETURN_GOOD) { fprintf(test_info.errout, "Unable to set %s transport: %s (%d)\n", (use_tls) ? "TLS" : (use_tcp) ? "TCP" : "UDP", getdns_get_errorstr_by_id(ret), ret); exit(EXIT_UNKNOWN); } } exit_value xit = f->func(&test_info, av); const char *xit_text = "(\?\?\?)"; FILE *out = stdout; switch(xit) { case EXIT_OK: xit_text = "OK"; break; case EXIT_WARNING: xit_text = "WARNING"; break; case EXIT_CRITICAL: xit_text = "CRITICAL"; break; case EXIT_UNKNOWN: case EXIT_USAGE: xit = EXIT_UNKNOWN; xit_text = "UNKNOWN"; out = test_info.errout; break; } if (test_info.monitoring) fprintf(out, "DNS SERVER %s - ", xit_text); fputs(test_info.base_output, out); if (test_info.verbosity >= VERBOSITY_ADDITIONAL && test_info.monitoring && strlen(test_info.perf_output) > 0) { fprintf(out, "|%s", test_info.perf_output); } fputc('\n', out); exit(xit); } getdns-1.5.1/src/tools/getdns_query.c0000644000175000017500000016074713416117763014557 00000000000000/* * Copyright (c) 2013, NLNet Labs, Verisign, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the names of the copyright holders nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 Verisign, Inc. 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 "config.h" #include "debug.h" #include #include #include #include #include #include #include #ifndef USE_WINSOCK #include #include #include #else #include #include typedef unsigned short in_port_t; #include #include #endif #ifdef HAVE_SIGNAL_H #include #endif #ifdef HAVE_GETDNS_YAML2DICT getdns_return_t getdns_yaml2dict(const char *, getdns_dict **dict); #endif #define EXAMPLE_PIN "pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\"" static int verbosity = 0; static int clear_listen_list_on_arg = 0; static int quiet = 0; static int batch_mode = 0; static char *query_file = NULL; static int json = 0; static char *the_root = "."; static char *name; static getdns_context *context; static getdns_dict *extensions; static getdns_dict *query_extensions_spc = NULL; static getdns_list *pubkey_pinset = NULL; static getdns_list *listen_list = NULL; int touched_listen_list; static getdns_dict *listen_dict = NULL; static size_t pincount = 0; static size_t listen_count = 0; static uint16_t request_type = GETDNS_RRTYPE_NS; static int timeout, edns0_size, padding_blocksize; static int async = 0, interactive = 0; static enum { GENERAL, ADDRESS, HOSTNAME, SERVICE } calltype = GENERAL; static int bogus_answers = 0; static int check_dnssec = 0; #ifndef USE_WINSOCK static char *resolvconf = NULL; #endif static int print_api_info = 0, print_trust_anchors = 0; static int log_level = 0; static uint64_t log_systems = 0xFFFFFFFFFFFFFFFF; static int get_rrtype(const char *t) { char buf[1024] = "GETDNS_RRTYPE_"; uint32_t rrtype; long int l; size_t i; char *endptr; if (strlen(t) > sizeof(buf) - 15) return -1; for (i = 14; *t && i < sizeof(buf) - 1; i++, t++) buf[i] = *t == '-' ? '_' : toupper(*t); buf[i] = '\0'; if (!getdns_str2int(buf, &rrtype)) return (int)rrtype; if (strncasecmp(buf + 14, "TYPE", 4) == 0) { l = strtol(buf + 18, &endptr, 10); if (!*endptr && l >= 0 && l < 65536) return l; } return -1; } static int get_rrclass(const char *t) { char buf[1024] = "GETDNS_RRCLASS_"; uint32_t rrclass; long int l; size_t i; char *endptr; if (strlen(t) > sizeof(buf) - 16) return -1; for (i = 15; *t && i < sizeof(buf) - 1; i++, t++) buf[i] = toupper(*t); buf[i] = '\0'; if (!getdns_str2int(buf, &rrclass)) return (int)rrclass; if (strncasecmp(buf + 15, "CLASS", 5) == 0) { l = strtol(buf + 20, &endptr, 10); if (!*endptr && l >= 0 && l < 65536) return l; } return -1; } static getdns_return_t fill_transport_list(char *transport_list_str, getdns_transport_list_t *transports, size_t *transport_count) { size_t max_transports = *transport_count; *transport_count = 0; for ( size_t i = 0 ; i < max_transports && i < strlen(transport_list_str) ; i++, (*transport_count)++) { switch(*(transport_list_str + i)) { case 'U': transports[i] = GETDNS_TRANSPORT_UDP; break; case 'T': transports[i] = GETDNS_TRANSPORT_TCP; break; case 'L': transports[i] = GETDNS_TRANSPORT_TLS; break; default: fprintf(stderr, "Unrecognised transport '%c' in string %s\n", *(transport_list_str + i), transport_list_str); return GETDNS_RETURN_GENERIC_ERROR; } } return GETDNS_RETURN_GOOD; } void print_usage(FILE *out, const char *progname) { fprintf(out, "usage: %s [