From 9ba1c9be16448c303e2a91c846b7891881b781a3 Mon Sep 17 00:00:00 2001 From: Willy Tarreau Date: Wed, 6 Oct 2021 15:29:00 +0200 Subject: [PATCH] MINOR: sample: provide a generic var-to-sample conversion function We're using variable-to-sample conversion at least 4 times in the code, two of which are bogus. Let's introduce a generic conversion function that performs the required checks. (cherry picked from commit 168e8de1d06adc7aa3e7e2cc2a36935a77c79b9c) [cf: call to vars_get_by_desc() was updated to remove the third param] Signed-off-by: Christopher Faulet (cherry picked from commit ea5735057fcf62c74b28fe3f13a0ab96b8014852) Signed-off-by: Christopher Faulet --- include/haproxy/sample.h | 1 + src/sample.c | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/include/haproxy/sample.h b/include/haproxy/sample.h index 963c147..720b02e 100644 --- a/include/haproxy/sample.h +++ b/include/haproxy/sample.h @@ -40,6 +40,7 @@ struct sample *sample_process(struct proxy *px, struct session *sess, struct sample *sample_fetch_as_type(struct proxy *px, struct session *sess, struct stream *strm, unsigned int opt, struct sample_expr *expr, int smp_type); +int sample_conv_var2smp(const struct var_desc *var, struct sample *smp, int type); int sample_conv_var2smp_sint(const struct arg *arg, struct sample *smp); int sample_conv_var2smp_str(const struct arg *arg, struct sample *smp); void release_sample_expr(struct sample_expr *expr); diff --git a/src/sample.c b/src/sample.c index 9a9fc23..51b3bc6 100644 --- a/src/sample.c +++ b/src/sample.c @@ -1555,6 +1555,25 @@ static int sample_conv_bin2base64(const struct arg *arg_p, struct sample *smp, v return 1; } + +/* This function returns a sample struct filled with the conversion of variable + * to sample type (SMP_T_*), via a cast to the target type. If the + * variable cannot be retrieved or casted, 0 is returned, otherwise 1. + * + * Keep in mind that the sample content may be written to a pre-allocated + * trash chunk as returned by get_trash_chunk(). + */ +int sample_conv_var2smp(const struct var_desc *var, struct sample *smp, int type) +{ + if (!vars_get_by_desc(var, smp)) + return 0; + if (!sample_casts[smp->data.type][type]) + return 0; + if (!sample_casts[smp->data.type][type](smp)) + return 0; + return 1; +} + static int sample_conv_sha1(const struct arg *arg_p, struct sample *smp, void *private) { blk_SHA_CTX ctx; -- 1.7.10.4