Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mg_printf - return -1 if strlen(fmt) > MG_BUF_LEN #70

Closed
pavel-pimenov opened this issue Dec 27, 2012 · 3 comments
Closed

mg_printf - return -1 if strlen(fmt) > MG_BUF_LEN #70

pavel-pimenov opened this issue Dec 27, 2012 · 3 comments

Comments

@pavel-pimenov
Copy link
Contributor

http://msdn.microsoft.com/en-us/library/1kt27hek%28v=vs.80%29.aspx
vsnprintf,_vsnprintf, and _vsnwprintf return the number of characters written if the number of characters to write is less than or equal to count; if the number of characters to write is greater than count, these functions return -1 indicating that output has been truncated. The return value does not include the terminating null, if one is written.

Test code:

include <stdio.h>

include <stdarg.h>

int mg_printf(const char *fmt, ...) {
char mem[10];
int len;
va_list ap;
// Print in a local buffer first, hoping that it is large enough to
// hold the whole message
va_start(ap, fmt);
len = vsnprintf(mem, sizeof(mem), fmt, ap);
va_end(ap);
printf("len = %d", len);
return len;
}

int main()
{
mg_printf(0,"%d - long stringlong stringlong stringlong string ",123);
return 0;
}

stdout:
len = -1

Temp fix:

int mg_printf_dynamic(struct mg_connection *conn, const int len_helper, const char *fmt, ...)
{
va_list ap;
int len = -1;
int l_fly_size = len_helper;
char *l_fly_buf = (char *)malloc(l_fly_size);
if(l_fly_buf)
{
l_fly_buf[0] = 0;
va_start(ap, fmt);
while(_vsnprintf(l_fly_buf, l_fly_size, fmt, ap) == -1){
free(l_fly_buf);
l_fly_size *= 2;
l_fly_buf = (char *)malloc(l_fly_size);
if(!l_fly_buf)
return -1;
l_fly_buf[0] = 0;
}
va_end(ap);
len = mg_write(conn, l_fly_buf, (size_t) l_fly_size);
free(l_fly_buf);
}
return len;
}

@jmucchiello
Copy link
Contributor

That code is not right. You should not call mg_write with l_fly_size. You should call it with the return value from _vsnprintf!

...
va_start(ap, fmt);
int actual_size;
while ((actual_size = _vsnprintf(l_fly_buf, l_fly_size, fmt, ap)) == -1) {
...
}
va_end(ap);
len = mg_write(conn, l_fly_buff, (size_t)actual_size);
...

@pavel-pimenov
Copy link
Contributor Author

thanks!

@cpq
Copy link
Member

cpq commented Jan 25, 2013

That is fixed in b589e0c
I've added alloc_vprintf() function. It looks like if the buffer is 0, windows snprintf() behaves correctly.
I assume this is the case for all versions of msvcrt.dll

@cpq cpq closed this as completed Jan 25, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants