comparison buffer.c @ 21:ae4128d16c92

Improve security and FIXED size buffer
author David Demelier <markand@malikania.fr>
date Fri, 09 Sep 2011 17:32:53 +0200
parents 520939b40002
children 904a373aa120
comparison
equal deleted inserted replaced
20:a7ff7f59c7f6 21:ae4128d16c92
62 62
63 length = strlen(str); 63 length = strlen(str);
64 if (buffer_grow(buf, length) < 0) 64 if (buffer_grow(buf, length) < 0)
65 return -1; 65 return -1;
66 66
67 if (buf->flags & BUFFER_FIXED) 67 if (!(buf->flags & BUFFER_AUTO))
68 length = buf->size - buf->length - 1; 68 length = buf->size - buf->length - 1;
69 69
70 strncat(buf->data, str, length); 70 strncpy(buf->data + buf->length, str, length);
71 buf->length = strlen(buf->data); 71 buf->length = strlen(buf->data);
72 72
73 return 0; 73 return 0;
74 } 74 }
75 75
79 79
80 int 80 int
81 buffer_putc(struct buffer *buf, char c) 81 buffer_putc(struct buffer *buf, char c)
82 { 82 {
83 if (buffer_grow(buf, 1) < 0) 83 if (buffer_grow(buf, 1) < 0)
84 return -1;
85
86 if (!(buf->flags & BUFFER_AUTO) && buf->size - buf->length - 1 <= 2)
84 return -1; 87 return -1;
85 88
86 buf->data[buf->length++] = c; 89 buf->data[buf->length++] = c;
87 buf->data[buf->length] = '\0'; 90 buf->data[buf->length] = '\0';
88 91
98 { 101 {
99 if (buffer_grow(buf, size) < 0) 102 if (buffer_grow(buf, size) < 0)
100 return -1; 103 return -1;
101 104
102 /* Do not truncate void pointer */ 105 /* Do not truncate void pointer */
103 if (buf->flags & BUFFER_FIXED && size > (buf->size - buf->length - 1)) 106 if (!(buf->flags & BUFFER_AUTO) && size > (buf->size - buf->length - 1))
104 return -1; 107 return -1;
105 108
106 memcpy(buf->data + buf->length, data, size); 109 memcpy(buf->data + buf->length, data, size);
107 buf->length += size; 110 buf->length += size;
108 111
230 if ((buf->size - buf->length) > needed) 233 if ((buf->size - buf->length) > needed)
231 return 0; 234 return 0;
232 235
233 if (buf->flags & BUFFER_AUTO) { 236 if (buf->flags & BUFFER_AUTO) {
234 newlen = buf->size; 237 newlen = buf->size;
235 while (newlen - buf->length - 1 < needed) 238 while (newlen - buf->length - 1 <= needed)
236 newlen += buf->bsize; 239 newlen += buf->bsize;
237 240
238 if (!(buf->data = realloc(buf->data, buf->size))) 241 if (!(buf->data = realloc(buf->data, newlen)))
239 return -1; 242 return -1;
240 243
241 buf->size = newlen; 244 buf->size = newlen;
242 } else 245 memset(buf->data + buf->length, 0, buf->size - buf->length);
243 return (buf->bsize == buf->length) ? -1 : 0; 246 }
244 247
245 memset(buf->data + buf->length, 0, buf->size - buf->length); 248 return 0;
246 249 }
247 return 0;
248 }