3 * Copyright (c) 2007-2008, Jouni Malinen <j@w1.fi>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
9 * Alternatively, this software may be distributed under the terms of BSD
12 * See README and COPYING for more details.
20 static void wpabuf_overflow(const struct wpabuf
*buf
, size_t len
)
22 wpa_printf(MSG_ERROR
, "wpabuf %p (size=%lu used=%lu) overflow len=%lu",
23 buf
, (unsigned long) buf
->size
, (unsigned long) buf
->used
,
29 int wpabuf_resize(struct wpabuf
**_buf
, size_t add_len
)
31 struct wpabuf
*buf
= *_buf
;
32 if (buf
->used
+ add_len
> buf
->size
) {
35 nbuf
= os_realloc(buf
->ext_data
, buf
->used
+ add_len
);
38 os_memset(nbuf
+ buf
->used
, 0, add_len
);
41 nbuf
= os_realloc(buf
, sizeof(struct wpabuf
) +
45 buf
= (struct wpabuf
*) nbuf
;
46 os_memset(nbuf
+ sizeof(struct wpabuf
) + buf
->used
, 0,
50 buf
->size
= buf
->used
+ add_len
;
58 * wpabuf_alloc - Allocate a wpabuf of the given size
59 * @len: Length for the allocated buffer
60 * Returns: Buffer to the allocated wpabuf or %NULL on failure
62 struct wpabuf
* wpabuf_alloc(size_t len
)
64 struct wpabuf
*buf
= os_zalloc(sizeof(struct wpabuf
) + len
);
72 struct wpabuf
* wpabuf_alloc_ext_data(u8
*data
, size_t len
)
74 struct wpabuf
*buf
= os_zalloc(sizeof(struct wpabuf
));
86 struct wpabuf
* wpabuf_alloc_copy(const void *data
, size_t len
)
88 struct wpabuf
*buf
= wpabuf_alloc(len
);
90 wpabuf_put_data(buf
, data
, len
);
95 struct wpabuf
* wpabuf_dup(const struct wpabuf
*src
)
97 struct wpabuf
*buf
= wpabuf_alloc(wpabuf_len(src
));
99 wpabuf_put_data(buf
, wpabuf_head(src
), wpabuf_len(src
));
105 * wpabuf_free - Free a wpabuf
106 * @buf: wpabuf buffer
108 void wpabuf_free(struct wpabuf
*buf
)
112 os_free(buf
->ext_data
);
117 void * wpabuf_put(struct wpabuf
*buf
, size_t len
)
119 void *tmp
= wpabuf_mhead_u8(buf
) + wpabuf_len(buf
);
121 if (buf
->used
> buf
->size
) {
122 wpabuf_overflow(buf
, len
);
129 * wpabuf_concat - Concatenate two buffers into a newly allocated one
132 * Returns: wpabuf with concatenated a + b data or %NULL on failure
134 * Both buffers a and b will be freed regardless of the return value. Input
135 * buffers can be %NULL which is interpreted as an empty buffer.
137 struct wpabuf
* wpabuf_concat(struct wpabuf
*a
, struct wpabuf
*b
)
139 struct wpabuf
*n
= NULL
;
146 len
+= wpabuf_len(a
);
148 len
+= wpabuf_len(b
);
150 n
= wpabuf_alloc(len
);
153 wpabuf_put_buf(n
, a
);
155 wpabuf_put_buf(n
, b
);