Language: C
Label: safe
CWE: CWE-116 \u2014 Improper Encoding or Escaping of Output
The product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.

Code:
sudo_lbuf_append_esc_v1(struct sudo_lbuf *lbuf, int flags, const char *fmt, ...)
{
    unsigned int saved_len = lbuf->len;
    bool ret = false;
    const char *s;
    va_list ap;
    debug_decl(sudo_lbuf_append_esc, SUDO_DEBUG_UTIL);

    if (sudo_lbuf_error(lbuf))
	debug_return_bool(false);

#define should_escape(ch) \
    ((ISSET(flags, LBUF_ESC_CNTRL) && iscntrl((unsigned char)ch)) || \
    (ISSET(flags, LBUF_ESC_BLANK) && isblank((unsigned char)ch)))
#define should_quote(ch) \
    (ISSET(flags, LBUF_ESC_QUOTE) && (ch == '\'' || ch == '\\'))

    va_start(ap, fmt);
    while (*fmt != '\0') {
	if (fmt[0] == '%' && fmt[1] == 's') {
	    if ((s = va_arg(ap, char *)) == NULL)
		s = "(NULL)";
	    while (*s != '\0') {
		if (should_escape(*s)) {
		    if (!sudo_lbuf_expand(lbuf, sizeof("#0177") - 1))
			goto done;
		    lbuf->len += escape(*s++, lbuf->buf + lbuf->len);
		    continue;
		}
		if (should_quote(*s)) {
		    if (!sudo_lbuf_expand(lbuf, 2))
			goto done;
		    lbuf->buf[lbuf->len++] = '\\';
		    lbuf->buf[lbuf->len++] = *s++;
		    continue;
		}
		if (!sudo_lbuf_expand(lbuf, 1))
		    goto done;
		lbuf->buf[lbuf->len++] = *s++;
	    }
	    fmt += 2;
	    continue;
	}
	if (should_escape(*fmt)) {
	    if (!sudo_lbuf_expand(lbuf, sizeof("#0177") - 1))
		goto done;
	    if (*fmt == '\'') {
		lbuf->buf[lbuf->len++] = '\\';
		lbuf->buf[lbuf->len++] = *fmt++;
	    } else {
		lbuf->len += escape(*fmt++, lbuf->buf + lbuf->len);
	    }
	    continue;
	}
	if (!sudo_lbuf_expand(lbuf, 1))
	    goto done;
	lbuf->buf[lbuf->len++] = *fmt++;
    }
    ret = true;

done:
    if (!ret)
	lbuf->len = saved_len;
    if (lbuf->size != 0)
	lbuf->buf[lbuf->len] = '\0';
    va_end(ap);

    debug_return_bool(ret);
}