From 1e453d1f972821021749258fb2b393813fb4e940 Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Mon, 27 Apr 2015 20:48:29 +0100 Subject: [PATCH] Some miscellaneous marshalling helpers. I'm about to use these in a new piece of code, but they may come in helpful elsewhere as well. match_ssh_id in particular wraps an idiom that's quite common in the rest of the codebase. --- misc.c | 34 ++++++++++++++++++++++++++++++++++ misc.h | 17 +++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/misc.c b/misc.c index 94b5ac8a..0d5673b3 100644 --- a/misc.c +++ b/misc.c @@ -9,6 +9,7 @@ #include #include #include "putty.h" +#include "misc.h" /* * Parse a string block size specification. This is approximately a @@ -1035,3 +1036,36 @@ int smemeq(const void *av, const void *bv, size_t len) * we want to return 1, so then we can just shift down. */ return (0x100 - val) >> 8; } + +int match_ssh_id(int stringlen, const void *string, const char *id) +{ + int idlen = strlen(id); + return (idlen == stringlen && !memcmp(string, id, idlen)); +} + +void *get_ssh_string(int *datalen, const void **data, int *stringlen) +{ + void *ret; + int len; + + if (*datalen < 4) + return NULL; + len = GET_32BIT_MSB_FIRST((const unsigned char *)*data); + if (*datalen < len+4) + return NULL; + ret = (void *)((const char *)*data + 4); + *datalen -= len + 4; + *data = (const char *)*data + len + 4; + *stringlen = len; + return ret; +} + +int get_ssh_uint32(int *datalen, const void **data, unsigned *ret) +{ + if (*datalen < 4) + return FALSE; + *ret = GET_32BIT_MSB_FIRST((const unsigned char *)*data); + *datalen -= 4; + *data = (const char *)*data + 4; + return TRUE; +} diff --git a/misc.h b/misc.h index c38266d0..2c60748c 100644 --- a/misc.h +++ b/misc.h @@ -78,6 +78,23 @@ void smemclr(void *b, size_t len); * by the 'eq' in the name. */ int smemeq(const void *av, const void *bv, size_t len); +/* Extracts an SSH-marshalled string from the start of *data. If + * successful (*datalen is not too small), advances data/datalen past + * the string and returns a pointer to the string itself and its + * length in *stringlen. Otherwise does nothing and returns NULL. + * + * Like strchr, this function can discard const from its parameter. + * Treat it as if it was a family of two functions, one returning a + * non-const string given a non-const pointer, and one taking and + * returning const. */ +void *get_ssh_string(int *datalen, const void **data, int *stringlen); +/* Extracts an SSH uint32, similarly. Returns TRUE on success, and + * leaves the extracted value in *ret. */ +int get_ssh_uint32(int *datalen, const void **data, unsigned *ret); +/* Given a not-necessarily-zero-terminated string in (length,data) + * form, check if it equals an ordinary C zero-terminated string. */ +int match_ssh_id(int stringlen, const void *string, const char *id); + /* * Debugging functions. * -- 2.45.2