I’m writing a simple function that split binary/post-data/html from a HTTP response. The HTTP headers are terminated by \r\n\r\n the rest is the message.
I have wrote this:
#define MAX_BUFFER_SIZE 256
//...
int size = 0;
int buf_size = MAX_BUFFER_SIZE;
char * headers = malloc(MAX_BUFFER_SIZE);
char * newbuf;
while(httpresponse[size]) {
if(httpresponse[size] == '\r' &&
httpresponse[size + 1] == '\n' &&
httpresponse[size + 2] == '\r' &&
httpresponse[size + 3] == '\n') {
break;
}
headers[size] = httpresponse[size];
if(size >= buf_size) {
buf_size += MAX_BUFFER_SIZE;
newbuf = realloc(headers, buf_size);
if(NULL == newbuf) exit(1);
headers = newbuf;
}
size ++;
}
printf("%s\n", headers);
the httpresponse variable, has value-like:
HTTP/1.1 200 OK
Date: Fri, 23 Mar 2012 15:28:17 GMT
Expires: Sat, 23 Mar 2013 15:28:17 GMT
Cache-Control: public, max-age=31536000
Last-Modified: Thu, 14 Apr 2011 15:46:35 GMT
Content-Type: image/jpeg
Content-Length: 12745
X-XSS-Protection: 1; mode=block
Connection: close
���������I1��} �g������'�B�f�p���ohd]sft�����J�������1����瘿ٱ����$3�G�8��4=�E�i����ܼG����H��nbi�"�1��b[Ǘl��++���OPt�W��>�����i�]t�QT�N/,Q�Qz������0�` N7���M��f��S�Š�x9k��$*
//more binary...
but the above C program, print the following text:
HTTP/1.1 200 OK
Date: Fri, 23 Mar 2012 17:12:09 GMT
Expires: Sat, 23 Mar 2013 17:12:09 GMT
Last-Modified: Thu, 14 Apr 2011 15:46:35 GMT
Content-Type: image/jpeg
Content-Length: 12745
X-XSS-Protection: 1; mode=block
Cache-Control: public, max-age=31536000
Age: 3746
�2�/���ms���|ނ����LQr2K3�v��J.�,�z��^Oy����s(ct���X`iA����I����U�{
instead of:
HTTP/1.1 200 OK
Date: Fri, 23 Mar 2012 15:28:17 GMT
Expires: Sat, 23 Mar 2013 15:28:17 GMT
Cache-Control: public, max-age=31536000
Last-Modified: Thu, 14 Apr 2011 15:46:35 GMT
Content-Type: image/jpeg
Content-Length: 12745
X-XSS-Protection: 1; mode=block
Connection: close
how to fix this? Thanks in advance.
I think your code is OK except that malloc doens’t initialize the memory it allocates. This means when you BREAK out of your while loop the “headers” string you’ve captured doesn’t have a null byte terminating it.
Two ways to fix – ether use “calloc” which initializes the memory to binary zeroes or insert one line of code before your call to printf:
Cheers