bool test_sn_coap_parser()
{
    if( sn_coap_parser_alloc_message(NULL) ) {
        return false;
    }

    if( sn_coap_parser_alloc_options(NULL, NULL) ) {
        return false;
    }

    retCounter = 0;
    bool ret = true;
    // use zero-initialized buffer for tests
    uint8_t* ptr = (uint8_t*)calloc(20, 1);
    assert(ptr);
    sn_coap_hdr_s * hdr = sn_coap_parser(NULL, 8, ptr, NULL);
    if( hdr != NULL ){
        free(hdr);
        ret = false;
    }

    if( ret ){
        struct coap_s* coap = (struct coap_s*)malloc(sizeof(struct coap_s));
        coap->sn_coap_protocol_malloc = myMalloc;
        coap->sn_coap_protocol_free = myFree;
        retCounter = 0;
        coap_version_e* ver = (coap_version_e*)malloc(sizeof(coap_version_e));
        hdr = sn_coap_parser(coap, 8, ptr, ver);
        if( hdr != NULL ){
            free(hdr);
            ret = false;
        }

        if( ret ){
            retCounter = 1;
            hdr = sn_coap_parser(coap, 8, ptr, ver);
            if( !hdr || (hdr && hdr->coap_status != COAP_STATUS_PARSER_ERROR_IN_HEADER) ){
                free(hdr);
                ret = false;
            }
            if (hdr)
                sn_coap_parser_release_allocated_coap_msg_mem(coap, hdr);
        }
        free(ver);
        free(coap);

    }

    free(ptr);
    return ret;
}
Example #2
0
sn_coap_hdr_s *sn_coap_build_response(struct coap_s *handle, sn_coap_hdr_s *coap_packet_ptr, uint8_t msg_code)
{
    sn_coap_hdr_s *coap_res_ptr;

    if (!coap_packet_ptr || !handle) {
        return NULL;
    }

    coap_res_ptr = sn_coap_parser_alloc_message(handle);
    if (!coap_res_ptr) {
        tr_error("sn_coap_build_response - failed to allocate message!");
        return NULL;
    }

    if (coap_packet_ptr->msg_type == COAP_MSG_TYPE_CONFIRMABLE) {
        coap_res_ptr->msg_type = COAP_MSG_TYPE_ACKNOWLEDGEMENT;
        coap_res_ptr->msg_code = (sn_coap_msg_code_e)msg_code;
        coap_res_ptr->msg_id = coap_packet_ptr->msg_id;
    }

    else if (coap_packet_ptr->msg_type == COAP_MSG_TYPE_NON_CONFIRMABLE) {
        coap_res_ptr->msg_type = COAP_MSG_TYPE_NON_CONFIRMABLE;
        coap_res_ptr->msg_code = (sn_coap_msg_code_e)msg_code;
        /* msg_id needs to be set by the caller in this case */
    }

    else {
        handle->sn_coap_protocol_free( coap_res_ptr );
        return NULL;
    }

    if (coap_packet_ptr->token_ptr) {
        coap_res_ptr->token_len = coap_packet_ptr->token_len;
        coap_res_ptr->token_ptr = handle->sn_coap_protocol_malloc(coap_res_ptr->token_len);
        if (!coap_res_ptr->token_ptr) {
            tr_error("sn_coap_build_response - failed to allocate token!");
            handle->sn_coap_protocol_free(coap_res_ptr);
            return NULL;
        }
        memcpy(coap_res_ptr->token_ptr, coap_packet_ptr->token_ptr, coap_res_ptr->token_len);
    }
    return coap_res_ptr;
}