diff --git a/context.c b/context.c index b816e1540..cf17d282e 100644 --- a/context.c +++ b/context.c @@ -20,7 +20,6 @@ #include "iio-config.h" #include "iio-private.h" #include "sort.h" -#include "network.h" #include #include @@ -328,22 +327,13 @@ struct iio_context * iio_create_context_from_uri(const char *uri) struct iio_context * iio_create_default_context(void) { - char *hostname = getenv("IIOD_REMOTE"); + char *hostname = iio_getenv("IIOD_REMOTE"); + struct iio_context * ctx; if (hostname) { - if (strlen(hostname) > 2 && strlen(hostname) < MAXHOSTNAMELEN + 4) { - struct iio_context *ctx; - - ctx = iio_create_context_from_uri(hostname); - if (ctx) - return ctx; - } -#ifdef HAVE_DNS_SD - /* If the environment variable is an empty string, we will - * discover the server using ZeroConf */ - if (!hostname[0]) - return iio_create_network_context(NULL); -#endif + ctx = iio_create_context_from_uri(hostname); + free(hostname); + return ctx; } return iio_create_local_context(); diff --git a/iio-private.h b/iio-private.h index 4e82b3d22..302f7eb84 100644 --- a/iio-private.h +++ b/iio-private.h @@ -314,6 +314,7 @@ unsigned int find_channel_modifier(const char *s, size_t *len_p); char *iio_strdup(const char *str); size_t iio_strlcpy(char * __restrict dst, const char * __restrict src, size_t dsize); +char * iio_getenv (char * envvar); int iio_context_add_attr(struct iio_context *ctx, const char *key, const char *value); diff --git a/utilities.c b/utilities.c index a41ed7cf7..d90ddff9b 100644 --- a/utilities.c +++ b/utilities.c @@ -21,6 +21,7 @@ #include "iio-config.h" #include "iio-private.h" +#include "network.h" #include #include @@ -256,3 +257,45 @@ size_t iio_strlcpy(char * __restrict dst, const char * __restrict src, size_t ds return(src - osrc - 1); /* count does not include NUL */ } + +/* Cross platform version of getenv */ + +char * iio_getenv (char * envvar) +{ + char *hostname; + size_t len, tmp; + +#ifdef _MSC_BUILD + if (_dupenv_s(&hostname, NULL, envvar)) + return NULL; +#else + hostname = getenv(envvar); +#endif + + if (!hostname) + return NULL; + + tmp = MAXHOSTNAMELEN + sizeof("serial:") + sizeof(":65535") - 2; + len = strnlen(hostname, tmp); + + /* Should be smaller than max length */ + if (len <= tmp) + goto wrong_str; + + /* should be more than "usb:" or "ip:" */ + tmp = sizeof("ip:") - 1; + if (len < tmp) + goto wrong_str; + +#ifdef _MSC_BUILD + return hostname; +#else + return strdup (hostname); +#endif + +wrong_str: +#ifdef _WIN32 + free(hostname); +#endif + return NULL; +}