xl: Rewrite trim()

This function would produce a NULL output pointer if the input was an
empty string, leading to a crash.

I don't think this is likely to be a security problem, as the two call
sites involve configuration options which callers are unlikely to
expose to other-than-fully-trusted input.

Also, the function would needlessly copy the input string (which I
care about not for performance reasons but because it makes the memory
handling more confusing), and would mishandle strings which contained
only predicate-true characters.

Signed-off-by: Ian Jackson <Ian.Jackson@eu.citrix.com>
Acked-by: Ian Campbell <ian.campbell@citrix.com>
Acked-by: Wei Liu <wei.liu2@citrix.com>
This commit is contained in:
Ian Jackson authored and Ian Jackson committed 2015-07-16 16:58:59 +01:00
1 parent 40e0895640
commit e316316fd6
1 file changed
+15 -18
+15 -18
View File
@@ -650,26 +650,23 @@ typedef int (*char_predicate_t)(const int c);
static void trim(char_predicate_t predicate, const char *input, char **output)
{
char *p, *q, *tmp;
const char *first, *after;
*output = NULL;
if (*input == '\000')
return;
/* Input has length >= 1 */
for (first = input;
*first && predicate((unsigned char)first[0]);
first++)
;
p = tmp = xstrdup(input);
/* Skip past the characters for which predicate is true */
while ((*p != '\000') && (predicate((unsigned char)*p)))
p ++;
q = p + strlen(p) - 1;
/* q points to the last non-NULL character */
while ((q > p) && (predicate((unsigned char)*q)))
q --;
/* q points to the last character we want */
q ++;
*q = '\000';
*output = xstrdup(p);
free(tmp);
for (after = first + strlen(first);
after > first && predicate((unsigned char)after[-1]);
after--)
;
size_t len_nonnull = after - first;
*output = xmalloc(len_nonnull + 1);
memcpy(output, first, len_nonnull);
output[len_nonnull] = 0;
}
static int split_string_into_pair(const char *str,
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.