coap_pdu_t * coap_pdu_init(unsigned char type, unsigned char code, unsigned short id, size_t size) { coap_pdu_t *pdu; #ifdef WITH_LWIP struct pbuf *p; #endif assert(size <= COAP_MAX_PDU_SIZE); /* Size must be large enough to fit the header. */ if (size < sizeof(coap_hdr_t) || size > COAP_MAX_PDU_SIZE) return NULL; /* size must be large enough for hdr */ #if defined(WITH_POSIX) || defined(WITH_CONTIKI) pdu = coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t)); if (!pdu) return NULL; pdu->hdr = coap_malloc_type(COAP_PDU_BUF, size); if (pdu->hdr == NULL) { coap_free_type(COAP_PDU, pdu); pdu = NULL; } #endif /* WITH_POSIX or WITH_CONTIKI */ #ifdef WITH_LWIP pdu = (coap_pdu_t*)coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t)); if (!pdu) return NULL; p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM); if (p == NULL) { coap_free_type(COAP_PDU, pdu); pdu = NULL; } #endif if (pdu) { #ifdef WITH_LWIP pdu->pbuf = p; #endif coap_pdu_clear(pdu, size); pdu->hdr->id = id; pdu->hdr->type = type; pdu->hdr->code = code; } return pdu; }
void coap_delete_pdu(coap_pdu_t *pdu) { #if defined(WITH_POSIX) || defined(WITH_CONTIKI) if (pdu != NULL) { if (pdu->hdr != NULL) { coap_free_type(COAP_PDU_BUF, pdu->hdr); } coap_free_type(COAP_PDU, pdu); } #endif #ifdef WITH_LWIP if (pdu != NULL) /* accepting double free as the other implementation accept that too */ pbuf_free(pdu->pbuf); coap_free_type(COAP_PDU, pdu); #endif }