static apr_status_t open_pktfile()

in wb/wb.c [1099:1167]


static apr_status_t open_pktfile(const char *pfile)
{
    apr_file_t *pktfd;
    apr_finfo_t finfo;
    apr_status_t rv;
    char errmsg[120];

    // open the file and get the file size
    rv = apr_file_open(&pktfd, pfile, APR_READ, APR_OS_DEFAULT, cntxt);
    if (rv != APR_SUCCESS) {
        fprintf(stderr, "wb: Could not open PKT data file (%s): %s\n", pfile,
                apr_strerror(rv, errmsg, sizeof errmsg));
        return rv;
    }
    rv = apr_file_info_get(&finfo, APR_FINFO_NORM, pktfd);
    if (rv != APR_SUCCESS) {
        fprintf(stderr, "wb: Could not stat PKT data file (%s): %s\n", pfile,
                apr_strerror(rv, errmsg, sizeof errmsg));
        return rv;
    }

    // allocate memeory for g_pkt_data to hold the entire file
    g_pkt_length = (apr_size_t)finfo.size;
    if (g_pkt_length <= 0) {
        fprintf(stderr, "wb: packets file(%s) is empty!\n", pfile);
        apr_file_close(pktfd);
        goto err_exit;
    }
    
    if (g_pkt_data) free(g_pkt_data);
    g_pkt_data = xmalloc(g_pkt_length);
    memset(g_pkt_data, 0, g_pkt_length);

    // read pkt file entirely into memory (g_pkt_data) and then close
    rv = apr_file_read_full(pktfd, g_pkt_data, g_pkt_length, NULL);
    if (rv != APR_SUCCESS) {
        fprintf(stderr, "wb: Could not read PKT data file: %s\n",
                apr_strerror(rv, errmsg, sizeof errmsg));
        return rv;
    }
    apr_file_close(pktfd);

    // now processing those packets, and get the packets number 
    // First, malloc space for pkt array to save the starting pointer of those sent packets
    if (g_MAX_PKT_COUNT == 0) // parse the packets string to get their count
        g_MAX_PKT_COUNT = parse_pktfile(g_pkt_data, NULL);
    
    if (g_MAX_PKT_COUNT == 0) {
        fprintf(stderr, "wb: packets file(%s) is invalid!\n", pfile);
        goto err_exit;
    }

    // allocate packet array memory and parse the packets again to save them
    g_pkt_array = xcalloc(g_MAX_PKT_COUNT, sizeof(struct _g_pkt_array_));
    g_pkt_count = parse_pktfile(g_pkt_data, g_pkt_array);
    //sort pkt by time
    if (g_pkt_count > 1) {
        qsort(g_pkt_array, g_pkt_count, sizeof(struct _g_pkt_array_), compare_pkt_by_time_to_send);
    }
    if (g_pkt_count > 1)
        nolength = 1; // no constant packet length if g_pkt_count >= 2

    return APR_SUCCESS;
    
err_exit:
    fprintf(stderr, "Error: wrong packet file (%s)!\n", pfile);
    if (g_pkt_data) free(g_pkt_data);
    exit (1);
} // end of open_pktfile