Skip to content

Commit 13dd730

Browse files
committed
version: refactor strbuf_sanitize()
The git_user_agent_sanitized() function performs some sanitizing to avoid special characters being sent over the line and possibly messing up with the protocol or with the parsing on the other side. Let's extract this sanitizing into a new strbuf_sanitize() function, as we will want to reuse it in a following patch, and let's put it into strbuf.{c,h}. While at it, let's also make a few small improvements: - use 'size_t' for 'i' instead of 'int', - move the declaration of 'i' inside the 'for ( ... )', - use strbuf_detach() to explicitly detach the string contained by the 'sb' strbuf. Helped-by: Eric Sunshine <[email protected]> Signed-off-by: Christian Couder <[email protected]>
1 parent 23692e0 commit 13dd730

File tree

3 files changed

+18
-7
lines changed

3 files changed

+18
-7
lines changed

strbuf.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,3 +1082,12 @@ void strbuf_strip_file_from_path(struct strbuf *sb)
10821082
char *path_sep = find_last_dir_sep(sb->buf);
10831083
strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);
10841084
}
1085+
1086+
void strbuf_sanitize(struct strbuf *sb)
1087+
{
1088+
strbuf_trim(sb);
1089+
for (size_t i = 0; i < sb->len; i++) {
1090+
if (sb->buf[i] <= 32 || sb->buf[i] >= 127)
1091+
sb->buf[i] = '.';
1092+
}
1093+
}

strbuf.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,13 @@ typedef int (*char_predicate)(char ch);
664664
void strbuf_addstr_urlencode(struct strbuf *sb, const char *name,
665665
char_predicate allow_unencoded_fn);
666666

667+
/*
668+
* Trim and replace each character with ascii code below 32 or above
669+
* 127 (included) using a dot '.' character. Useful for sending
670+
* capabilities.
671+
*/
672+
void strbuf_sanitize(struct strbuf *sb);
673+
667674
__attribute__((format (printf,1,2)))
668675
int printf_ln(const char *fmt, ...);
669676
__attribute__((format (printf,2,3)))

version.c

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,10 @@ const char *git_user_agent_sanitized(void)
2424

2525
if (!agent) {
2626
struct strbuf buf = STRBUF_INIT;
27-
int i;
2827

2928
strbuf_addstr(&buf, git_user_agent());
30-
strbuf_trim(&buf);
31-
for (i = 0; i < buf.len; i++) {
32-
if (buf.buf[i] <= 32 || buf.buf[i] >= 127)
33-
buf.buf[i] = '.';
34-
}
35-
agent = buf.buf;
29+
strbuf_sanitize(&buf);
30+
agent = strbuf_detach(&buf, NULL);
3631
}
3732

3833
return agent;

0 commit comments

Comments
 (0)