diff options
-rw-r--r-- | dbfp.c | 38 |
1 files changed, 28 insertions, 10 deletions
@@ -8,6 +8,7 @@ #include <errno.h> #include <expat.h> +#include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -36,6 +37,8 @@ static int dbfp_parse(void *contents, size_t len, size_t n, void *data); static int dbfp_request(struct dbfp *dbfp, char *service, char *query, XML_Parser parser); static int dbfp_url(struct dbfp *dbfp, char *service, char *query, char **url); +static int dbfp_format_url(struct dbfp *dbfp, char **out, const char *format, + ...); static int check_ele_error(const char *name, const char **atts); static int read_string(const char **atts, size_t idx, void *value); @@ -113,7 +116,6 @@ int dbfp_query_location_name(struct dbfp *dbfp, char *input, char *input_enc = NULL; char *query = NULL; XML_Parser parser = NULL; - int len; struct location_data ld = { .n = 0, .locations = NULL }; struct parse_data pd = { .error = 0, .data = &ld }; @@ -128,16 +130,9 @@ int dbfp_query_location_name(struct dbfp *dbfp, char *input, err = DBFP_ERROR_CURL; goto cleanup; } - query = malloc(DBFP_URL_LEN); - if (!query) { - err = ENOMEM; - goto cleanup; - } - len = snprintf(query, DBFP_URL_LEN, "input=%s", input_enc); - if (len < 0 || len >= DBFP_URL_LEN) { - err = DBFP_ERROR_FORMAT; + err = dbfp_format_url(dbfp, &query, "input=%s", input_enc); + if (err) goto cleanup; - } parser = XML_ParserCreateNS(NULL, '\0'); XML_SetUserData(parser, &pd); @@ -233,6 +228,29 @@ static int dbfp_url(struct dbfp *dbfp, char *service, char *query, char **url) return 0; } +static int dbfp_format_url(struct dbfp *dbfp, char **out, const char *format, + ...) +{ + va_list args; + int len; + + *out = malloc(DBFP_URL_LEN); + if (!*out) + return ENOMEM; + + va_start(args, format); + len = vsnprintf(*out, DBFP_URL_LEN, format, args); + va_end(args); + + if (len < 0 || len >= DBFP_URL_LEN) { + free(*out); + *out = NULL; + return DBFP_ERROR_FORMAT; + } + + return 0; +} + static int check_ele_error(const char *name, const char **atts) { if (strcmp(name, "Error") == 0) { |