Exemplo n.º 1
0
    size_t operator()(double val, Result& result)
    {
        size_t count = 0;

        chars_format format = override_.format() != chars_format() ? override_.format() : chars_format::general;

        int decimal_places;
        if (override_.decimal_places() != 0)
        {
            decimal_places = override_.decimal_places();
        }
        else
        {
            format = chars_format::general;
            decimal_places = 0;
        }             

        char number_buffer[200]; 
        int length = 0;

        switch (format)
        {
        case chars_format::fixed:
            {
                length = snprintf(number_buffer, sizeof(number_buffer), "%1.*f", decimal_places, val);
                if (length < 0)
                {
                    JSONCONS_THROW(json_runtime_error<std::invalid_argument>("print_double failed."));
                }
                dump_buffer(number_buffer, length, decimal_point_, result);
            }
            break;
        case chars_format::scientific:
            {
                length = snprintf(number_buffer, sizeof(number_buffer), "%1.*e", decimal_places, val);
                if (length < 0)
                {
                    JSONCONS_THROW(json_runtime_error<std::invalid_argument>("print_double failed."));
                }
                dump_buffer(number_buffer, length, decimal_point_, result);
            }
            break;
        case chars_format::general:
            {
                if (override_.precision() != 0)
                {
                    int precision = override_.precision();
                    length = snprintf(number_buffer, sizeof(number_buffer), "%1.*g", precision, val);
                    if (length < 0)
                    {
                        JSONCONS_THROW(json_runtime_error<std::invalid_argument>("print_double failed."));
                    }
                    dump_buffer(number_buffer, length, decimal_point_, result);
                }
                else
                {
                    if (!dtoa(val, decimal_point_, result))
                    {
                        JSONCONS_THROW(json_runtime_error<std::invalid_argument>("print_double failed."));
                    }
                }             
                break;
            }
            default:
                JSONCONS_THROW(json_runtime_error<std::invalid_argument>("print_double failed."));
                break;
        }
        return count;
    }
Exemplo n.º 2
0
int
exercise (int fd, char *rawdevice, long long blocks, int min_xfer_size,
          int max_xfer_size, int do_log)
{
    static pid_t pid;
    struct range
    {
        int range_number;
        int start;
        int length;
    };
    static struct range ranges[EXER_PROCESSCOUNT];
    struct buffer
    {
        int rbuffer[MAX_TRANSFER_SIZE / 4];
        int wbuffer[MAX_TRANSFER_SIZE / 4];
    }
    buff[EXER_PROCESSCOUNT];

    int little_buffer[128];
    static int iterations;
    static long size;
    static int i, j, p = 1, iw = 0;
    static long write_block_count = 0;
    static long read_block_count = 0;
    static long int charsread, charswrote;

#ifdef DEBUG
    long write_min_start, write_max_start;
    long min_size, max_size;
#endif

    static long long random_block;
    static long max_xfer, min_xfer;	/* transfer sizes in blocks */

    min_xfer_size = (min_xfer_size > 0) ? min_xfer_size : MIN_TRANSFER_SIZE;
    max_xfer_size = (max_xfer_size > 0) ? max_xfer_size : MAX_TRANSFER_SIZE;

    if (do_log == 1) {
        sprintf (buf, "Starting exerciser on device %s at ", rawdevice);
        logit (buf);
        current_time_to_log ();
    }

    iterations = EXER_ITERATIONS;
    max_xfer = max_xfer_size / 512;
    min_xfer = min_xfer_size / 512;

    /* Make sure we don't try to write off end... */
    blocks = blocks - (MAX_TRANSFER_SIZE / 512);

    /* Don't exercise block "0". There might be a label there. Besides, there   */
    /* are plenty of other blocks to test.                                      */
    ranges[0].start = 1;

    for (i = 0; i < EXER_PROCESSCOUNT; ++i) {
        ranges[i].range_number = i + 1;
        ranges[i].length = (int) blocks / EXER_PROCESSCOUNT;
        ranges[i + 1].start = (blocks / EXER_PROCESSCOUNT) * (i + 1) + 1;
    }

    for (i = 0; i < EXER_PROCESSCOUNT; ++i) {
        ranges[i].length = ranges[i].length - 150;
    }

    /* Fill the write buffer with random data */
    srand48 ((unsigned int) time (NULL));
    for (i = 0; i < (int) (MAX_TRANSFER_SIZE / 4); ++i) {
        buff[0].wbuffer[i] = drand48 () * INT_MAX;
    }

    srand ((unsigned int) time (NULL) + getpid ());

#if DEBUG
    min_size = min_xfer_size + 1;
    max_size = max_xfer_size - 1;
#endif

    for (p = 0; p < EXER_PROCESSCOUNT; ++p) {
        pid = fork ();
        if (pid == 0)
            break;
    }

    switch (pid) {
    case -1:
        exit (EXIT_FAILURE);
    case 0:

#ifdef DEBUG
        write_min_start = ranges[p].start + 10000;
        write_max_start = ranges[p].start + (ranges[p].length - 10000);
#endif

        srand48 ((unsigned int) time (NULL));
        while (iw < iterations) {
            random_block = (drand48 () * ranges[p].length) + ranges[p].start;

#ifdef DEBUG
            if (write_min_start > random_block)
                write_min_start = random_block;
            if (write_max_start < random_block)
                write_max_start = random_block;
#endif

            /*  generate random size for the transfer  */
            if (min_xfer_size != max_xfer_size) {
                size = 512 * ((rand () % ((max_xfer + 1) - min_xfer)) + 1) + (min_xfer_size - 512);
            } else {
                size = max_xfer_size;
            }

#if DEBUG
            if (min_size > size)
                min_size = size;
            if (max_size < size)
                max_size = size;
#endif

#ifdef _LARGEFILE64_SOURCE
            if ((lseek64 (fd, (off64_t) (random_block * 512), SEEK_SET)) < 0) {
                perror ("IOtest: lseek64");
                printf ("Seek didn't go to block %lld (on write)\n", (random_block));
                exit (EXIT_FAILURE);
            }
#else
            if ((lseek (fd, (long) (random_block * 512), SEEK_SET)) < 0) {
                perror ("IOtest: lseek");
                printf ("Seek didn't go to block %lld (on write)\n", (random_block * 512));
                exit (EXIT_FAILURE);
            }
#endif

            if ((charswrote = (long int) write (fd, buff[p].wbuffer, (size_t) size)) < 0) {
                printf ("Error during transfer of %ld bytes starting at block %Lu\n", size, random_block);
                perror ("IOtest:  write");
            }
            write_block_count = write_block_count + (size / 512);

#ifdef _LARGEFILE64_SOURCE
            if ((lseek64 (fd, (off64_t) (random_block * 512), SEEK_SET)) < 0) {
                perror ("IOtest: lseek64");
                printf ("Seek didn't go to block %lld (on read)\n", (random_block));
                exit (EXIT_FAILURE);
            }
#else
            if ((lseek (fd, (long) (random_block * 512), SEEK_SET)) < 0) {
                perror ("IOtest: lseek");
                printf ("Seek didn't go to block %lld (on read)\n", (random_block * 512));
                exit (EXIT_FAILURE);
            }
#endif

            if ((charsread = (long int) read (fd, buff[p].rbuffer, (size_t) size)) < 0) {
                printf ("Error during transfer of %ld bytes starting at block %Lu\n", size, random_block);
                perror ("IOtest: read");

            }
            read_block_count = read_block_count + (size / 512);



            /*********************/
            /*if ((memcmp(buff[p].wbuffer, buff[p].rbuffer, size)) != 0) { */
            /*printf("memcmp error found\n");*/
            /*}*/
            /*********************/

            /* compare the write and read buffers  */

            for (i = 0; i < (int) (size / 4); ++i) {
                if (buff[p].wbuffer[i] != buff[p].rbuffer[i]) {

                    while (p < 1) {	/*  sanity check. */
                        /*  only one process supported for the time being */

                        sprintf (buf, "\nError comparing write and read buffers\n");
                        printf ("%s", buf);
                        printf ("%ld block transfer starting at block number %lld\n", size / 512, random_block);
                        sprintf (buf,
                                 "Error is in 32 bits starting at byte %d in block number %lld\n",
                                 (i % 128) * 4, random_block + (i / 128));
                        printf ("%s", buf);
                        sprintf (buf,
                                 "Expected data = %08lX  Received data = %08lX\n",
                                 swap ((unsigned long int) buff[p].wbuffer[i]),
                                 swap ((unsigned long int) buff[p].rbuffer[i]));
                        printf ("%s", buf);

                        for (j = 0; j <= 127; ++j) {
                            little_buffer[j] = buff[p].rbuffer[((i / 128) * 512 / 4) + j];
                        }

                        sprintf (buf, "\nHEX dump of block %lld --  read from read buffer\n",
                                 random_block + (i / 128));
                        printf ("%s", buf);
                        dump_buffer (little_buffer);

                        printf ("\n\nRe-reading block number %lld\n", random_block + (1 / 128));
                        sprintf (buf, "HEX dump of block %lld -- read from %s\n", random_block + (i / 128),
                                 rawdevice);
                        printf ("%s", buf);
                        dump (fd, random_block + (i / 128), 1, do_log);

                        printf ("\n\nDo you want to continue (yes,no [no])?  ");
                        (void) fgets (inbuf, INBUFLEN, stdin);
                        if (sscanf (inbuf, "%s", ans) == EOF) {
                            error_flag = 1;
                            iw = iterations;
                            return (error_flag);
                        } else if ((strcmp (ans, "yes") == 0)
                                   || (strcmp (ans, "y") == 0)) {
                            error_flag = 0;
                            printf ("continuing...\n");
                            break;
                        } else if ((strcmp (ans, "no") == 0 || strcmp (ans, "n") == 0)) {
                            error_flag = 1;
                            iw = iterations;
                            /*printf ("error_flag = 1, exiting...\n"); */
                            exit (error_flag);
                        }
                    }
                }
            }
            iw++;			/* increment and do it again  */
        }

        if (write_block_count != read_block_count) {
            printf (" Big problem!!  The number of blocks read doesn't\n");
            printf (" match the number of blocks written!\n");
            exit (EXIT_FAILURE);
        }

        sprintf (buf, "%ld blocks written, read and compared\n", write_block_count);
        printf ("%s", buf);

#ifdef DEBUG
        printf ("min starting block = %ld  max starting block = %ld\n",
                write_min_start, write_max_start);
        printf
        ("min xfer size = %ld blocks    max xfer size = %ld blocks\n",
         min_size / 512, max_size / 512);
        printf ("child pid = %d\n", (int) getpid ());
#endif

        exit (EXIT_SUCCESS);
    default:

#ifdef DEBUG
        printf ("parent process pid = %d\n", (int) getpid ());
#endif

        break;
    }

    /*********************************************************************/
    /* Wait for EXER_PROCESSCOUNT child processes to finish, then return */
    /* EXER_PROCESSCOUNT should be 1.  Don't try to increase it yet!!    */
    /*********************************************************************/

    for (p = 1; p <= EXER_PROCESSCOUNT; ++p) {
        static pid_t child_pid;
        child_pid = wait (&error_flag);
    }
    return (error_flag);
}
Exemplo n.º 3
0
void Kinect2Manager::DumpBuffers() {
    CreateDirectoryA("dump/", NULL);

    dump_buffer("dump/depth_rgbx.bin", m_pDepthRGBX, sizeof(RGBQUAD), CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH);
    dump_buffer("dump/depth.bin", m_pDepth, sizeof(USHORT), CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH);
    dump_buffer("dump/color_rgbx.bin", m_pColorRGBX, sizeof(RGBQUAD), CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR);
    dump_buffer("dump/color_depth_map.bin", m_pColorDepthMap, sizeof(DepthSpacePoint), CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR);
    dump_buffer("dump/depth_color_map_rgbx.bin", m_pDepthColorMap, sizeof(ColorSpacePoint), CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH);
    dump_buffer("dump/depth_x_mapped_to_color.bin", m_pDepthXMappedToColor, sizeof(int), CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR);
    dump_buffer("dump/depth_y_mapped_to_color.bin", m_pDepthYMappedToColor, sizeof(int), CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR);
    dump_buffer("dump/depth_mapped_to_color.bin", m_pDepthMappedToColor, sizeof(USHORT), CAPTURE_SIZE_X_COLOR * CAPTURE_SIZE_Y_COLOR);
    dump_buffer("dump/color_x_mapped_to_depth.bin", m_pColorXMappedToDepth, sizeof(int), CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH);
    dump_buffer("dump/color_y_mapped_to_depth.bin", m_pColorYMappedToDepth, sizeof(int), CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH);
    dump_buffer("dump/color_mapped_to_depth.bin", m_pColorMappedToDepth, sizeof(RGBQUAD), CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH);
    dump_buffer("dump/body_index.bin", m_pBodyIndex, sizeof(unsigned char), CAPTURE_SIZE_X_DEPTH * CAPTURE_SIZE_Y_DEPTH);
    dump_buffer("dump/joints.bin", m_pJoints, sizeof(Joint), JointType_Count);
    dump_buffer("dump/joint_orientations.bin", m_pJointOrientations, sizeof(JointOrientation), JointType_Count);
    dump_buffer("dump/best_body_index.bin", &m_nBodyIndex, sizeof(UCHAR), 1);

}
static int test_03_modified_payload(uint32_t data)
{
    bool failed = false;
    bass_return_code result = BASS_RC_ERROR_UNKNOWN;
    bass_payload_type_t payload_type = BASS_PL_TYPE_X_LOADER;
    bass_hash_type_t hashtype = BASS_APP_SHA256_HASH;
    size_t ehash_size = SHA256_HASH_SIZE;
    uint8_t ehash[SHA256_HASH_SIZE];
    uint8_t *modified_payload = NULL;
    uint32_t payload_size = 0;
    uint32_t payload_offset = 0;

    (void)data;

    dprintf(INFO, "Starting test\n");
    memset(&ehash, 0, sizeof(ehash));

    result = get_ehash(signed_payload, signed_payload_size, payload_type,
                       ehash);
    if (result != BASS_RC_SUCCESS) {
        dprintf(ERROR, "failed to getting ehash\n");
        return result;
    }

    payload_offset = get_header_size(signed_payload);
    payload_size = get_payload_size(signed_payload);

    modified_payload = malloc(sizeof(uint8_t) * payload_size);
    if (!modified_payload) {
        return BASS_RC_FAILURE;
    }

    memcpy(modified_payload, signed_payload + payload_offset, payload_size);

    /*
     * Set the first 48 bytes to 0xFF (which is ok in in the payloads used in
     * this file, any number is good as long as it isn't greater than payload
     * size).
     * */
    memset(modified_payload, 0xFF, 48);

    result = bass_check_payload_hash(&hashtype,
                                 &payload_type,
                                 (void *)(modified_payload),
                                 payload_size,
                                 ehash,
                                 ehash_size);

    if (result == BASS_RC_SUCCESS) {
        dump_buffer("Expected hash", ehash, ehash_size);
        dump_buffer("Correct payload", signed_payload + payload_offset,
                    payload_size);
        dump_buffer("modified_payload", modified_payload, payload_size);

        dprintf(ERROR, "incorrectly got a successfull result when checking "
                "payload hash using modified payload\n");
        failed = true;
    }

    free(modified_payload);
    /*
     * Not that we expect this to fail internally, but to the function calling
     * this function it should be BASS_RC_SUCCESS test case went as expected.
     */
    return failed ? BASS_RC_FAILURE : BASS_RC_SUCCESS;
}
Exemplo n.º 5
0
static int do_spi_io(struct spi_device* lp_dev, u8* lp_send_buffer, u8* lp_recv_buffer, 
                     int buffer_size)
{
    int ret_value;
	struct spi_message msg;
    struct spi_transfer xfer = 
        {
            .len = buffer_size, 
            .tx_buf = (void*)lp_send_buffer,
            .rx_buf = (void*)lp_recv_buffer,
            .speed_hz = 1000000,
        };

    spi_message_init(&msg);
    spi_message_add_tail(&xfer, &msg);

    dev_info(&lp_dev->dev, "spi io: transfer size = %d\n", buffer_size);
    
    ret_value = spi_sync(lp_dev, &msg);

    if (IS_SUCCESS(ret_value))
    {
        dev_info(&lp_dev->dev, "spi io done.\n");
    }
    
    dev_info(&lp_dev->dev, "do_spi_io ret_value = %d\n", ret_value);

    return ret_value;
}


int do_io_transaction(struct spi_device* lp_dev, 
                      _IN_ struct spi_io_context* lp_io_context,
                      _IN_ u8* const lp_send_buffer, int send_buffer_size,
                      _OUT_ u8* lp_recv_buffer, int recv_buffer_size, 
                      _OUT_ int* lp_recved_size )
{
    int ret_value = ER_FAILED;

    int total_trafster = 0;
    int one_time_transfer = 0;
    int total_receive_size = 0;

    int remain_send_count = send_buffer_size;
    int remain_recv_count = 0;

    int is_recved_vaild_fh = 0;

    struct buffer* lp_send_operator = NULL;
    struct buffer* lp_recv_operator = NULL;

    struct buffer dummy_send_buffer;
    struct buffer dummy_recv_buffer;

    struct buffer send_buffer;
    struct buffer recv_buffer;

    INIT_BUFFER(&dummy_send_buffer,
                lp_io_context->send_dummy_buffer,
                lp_io_context->send_dummy_buffer_size);
    
    INIT_BUFFER(&dummy_recv_buffer,
                lp_io_context->recv_dummy_buffer,
                lp_io_context->recv_dummy_buffer_size);
    
    INIT_BUFFER(&send_buffer, lp_send_buffer, send_buffer_size);

    INIT_BUFFER(&recv_buffer, lp_recv_buffer, recv_buffer_size);

    /*need some check here, but still in think.*/

    total_trafster = send_buffer_size;
    while(total_trafster > 0)
    {
        int send_buffer_is_dummy;
        int recv_buffer_is_dummy;

        /*
          Step1. try calc out transfer bye count
        */
        if (0 != BUFFER_REMAIN_LENGTH(send_buffer))
        {
            lp_send_operator = &send_buffer;
            send_buffer_is_dummy = FALSE;
        }
        else
        {
            lp_send_operator = &dummy_send_buffer;
            send_buffer_is_dummy = TRUE;
        }

        if (0 != remain_recv_count 
            && is_recved_vaild_fh)
        {
            lp_recv_operator = &recv_buffer;
            recv_buffer_is_dummy = FALSE;
        }
        else
        {
            lp_recv_operator = &dummy_recv_buffer;
            recv_buffer_is_dummy = TRUE;
        }

        if (is_recved_vaild_fh)
        {
            RESET_BUFFER(&dummy_send_buffer);
            RESET_BUFFER(&dummy_recv_buffer);

            if (send_buffer_is_dummy && recv_buffer_is_dummy)
            {
                one_time_transfer = 0;
            }
            else
            {
                one_time_transfer = MIN(BUFFER_REMAIN_LENGTH(*lp_send_operator),
                                        BUFFER_REMAIN_LENGTH(*lp_recv_operator));
            }
        }
        else
        {
            /*
              can't reset dummy recv buffer because it contain last time received
              splited data
             */
            one_time_transfer = MIN(BUFFER_REMAIN_LENGTH(*lp_send_operator), 
                                    BUFFER_REMAIN_LENGTH(dummy_recv_buffer));                      
        }

        if (0 == one_time_transfer)
        {
            /*caller's receive buffer is not enough case.*/
            if ( 0 != remain_recv_count)
            {
                ret_value = ER_NO_ENOUGH_RECV_BUFFER;
            }

            break;
        }

        /*
          Step 2. Prepare and do transfer
         */
        dev_info(&lp_dev->dev, "before do_spi_io\n");
        ret_value = do_spi_io(lp_dev,
                              BUFFER_PTR(*lp_send_operator), 
                              BUFFER_PTR(*lp_recv_operator),
                              one_time_transfer);
        if (IS_FAILED(ret_value))
        {
            dev_err(&lp_dev->dev, "do_spi_io() failed! \n");
            break;
        }
        dev_info(&lp_dev->dev, "after do_spi_io\n");

        lp_send_operator->index += one_time_transfer;
        lp_recv_operator->index += one_time_transfer;

        remain_send_count = MAX(0, remain_send_count - one_time_transfer);
        remain_recv_count = MAX(0, remain_recv_count - one_time_transfer);
        total_trafster -= one_time_transfer;

        /*
          Step 3. check if we received valid frame header
         */
        if (!is_recved_vaild_fh)
        {
            int total_payload_size;
            int contained_payload_size;
            int fh_start_index;
            int is_valid_fh;
            
            is_valid_fh = verify_frame_head_and_get_payload_size(lp_recv_operator->lp_ptr, 
                                                                 BUFFER_USED_LENGTH(*lp_recv_operator),
                                                                 &total_payload_size,
                                                                 &contained_payload_size,
                                                                 &fh_start_index);
            if (IS_SUCCESS(is_valid_fh))
            {
                int copy_size = contained_payload_size + SIZE_OF_FRAME_HEAD;
                int need_recv_buffer_size = total_payload_size + SIZE_OF_FRAME_HEAD;

                /*received new frame head!*/
                remain_recv_count = total_payload_size - contained_payload_size;
                
                /*received frame head, so we update total transfer count here*/
                total_trafster = MAX(remain_recv_count, remain_send_count);

                /*
                printf("[packege check]: total payload = %d, contained = %d, fh_start = %d\n",
                       total_payload_size,
                       contained_payload_size,
                       fh_start_index);
                */

                /*copy all valid data to actual receive buffer head*/

                if (need_recv_buffer_size > BUFFER_REMAIN_LENGTH(recv_buffer))
                {
                    ret_value = ER_NO_ENOUGH_RECV_BUFFER;
                    break;
                }
                
                /*do not reset buffer, because we now support
                  received mulit-frame in one io cycle.
                 */
                //RESET_BUFFER(&recv_buffer);                

                memcpy(BUFFER_PTR(recv_buffer), 
                       lp_recv_operator->lp_ptr + fh_start_index,
                       copy_size);

                /*
                  save total received size here to support receive mulit-frame
                 */
                total_receive_size += need_recv_buffer_size;
                
                recv_buffer.index += copy_size;
                recv_buffer.length = total_receive_size;

                //                pr_err("dump: index = %d, length = %d\n",
                //       recv_buffer.index, recv_buffer.length);

                is_recved_vaild_fh = TRUE;
            }
            else
            {
                int is_recved_hf_prefix = ER_FAILED;

                remain_recv_count = 0;

                //copy SIZEOF_FRAME_HEAD bytes from tail to head
                memcpy(dummy_recv_buffer.lp_ptr,
                       BUFFER_PTR_FROM_USED_TAIL(*lp_recv_operator, SIZE_OF_FRAME_HEAD),
                       SIZE_OF_FRAME_HEAD);

                dummy_recv_buffer.index = SIZE_OF_FRAME_HEAD;

                /*check if the last SIZE_OF_FRAME_HEAD bytes contained frame head prefix,
                  we will read more data if it contained, to resovle slice case
                 */
                is_recved_hf_prefix = verify_frame_head_prefix(BUFFER_PTR_FROM_USED_TAIL(*lp_recv_operator, SIZE_OF_FRAME_HEAD),
                                                               SIZE_OF_FRAME_HEAD);
                /*
                  check if the received data included frame head prefix 0x53
                 */
                if (IS_SUCCESS(is_recved_hf_prefix))
                {
                    total_trafster += BUFFER_REMAIN_LENGTH(dummy_recv_buffer);
                    /*
                    printf("set total_transfer = %d\n", total_trafster);
                    */
                }
                
                is_recved_vaild_fh = FALSE;
            }
        }
        else
        {
            /*
              if we already received one frame, but still has some data need
              send, we need change is_recved_vaild_fh = FALSE to prepare receive
              the next frame
             */
#if 1
            if (remain_send_count > 0
                && 0 == remain_recv_count)
            {
                is_recved_vaild_fh = FALSE;
                RESET_BUFFER(&dummy_recv_buffer);
                //pr_err("psh: note: try receive mulit-frame.\n");
            }
#endif

        }
    }

#if 1   
    if (IS_FAILED(ret_value))
    {
        /*
          dump recvied buffer
         */
        
        dump_buffer(lp_recv_operator->lp_ptr, BUFFER_USED_LENGTH(*lp_recv_operator));
    }
    else
    {
        //dump_buffer(recv_buffer.lp_ptr, BUFFER_USED_LENGTH(recv_buffer));
    }
#endif


    lp_recved_size ? *lp_recved_size = BUFFER_USED_LENGTH(recv_buffer) : 0;

    return ret_value;

}
Exemplo n.º 6
0
int main(int argc, char *argv[]) {
	int ret;
	void *voidptr;
	int i;

	(void) argc; (void) argv;

	/* Char format. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "foo %c bar", 'Z');
	dump_buffer();

	/* Signed long format. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%ld %9ld", (long) 123, (long) 4321);
	dump_buffer();

	/* Signed long with zero padding. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%09ld", (long) 4321);
	dump_buffer();
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%03ld %03ld %03ld", (long) -4321, (long) -432, (long) -43);
	dump_buffer();

	/* Unsigned long with zero padding. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%03lu %03lu %03lu", (long) -4321, (long) -432, (long) -43);
	dump_buffer();

	/* Signed integer. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%d %9d", (int) 0, (int) 4321);
	dump_buffer();

	/* Signed negative integer, fixed field width. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%9d", (int) -321);
	dump_buffer();
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%09d", (int) -321);
	dump_buffer();
	printf("  -- printf comparison: %9d %09d\n", -321, -321);

	/* Hex formatting. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%03x %03lx 0x%08lx", (int) 510, (long) 5105, (long) 0xdeadbeef);
	dump_buffer();

	/* Pointer formatting, NULL and non-NULL. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%p %p", (void *) NULL, (void *) buffer);
	dump_buffer();

	/* File/line like format test. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%s:%d", "foo bar quux", 123);
	dump_buffer();

	/* Zero size output buffer. */
	init_buffer();
	duk_minimal_snprintf(buffer, 0, "%s:%d", "foo bar quux", 123);
	dump_buffer();
	init_buffer();
	duk_minimal_snprintf(buffer, 0, "");
	dump_buffer();

	/* NUL terminator boundary test. */
	init_buffer();
	duk_minimal_snprintf(buffer, 7, "foo: %s", "bar");
	dump_buffer();
	init_buffer();
	duk_minimal_snprintf(buffer, 8, "foo: %s", "bar");
	dump_buffer();
	init_buffer();
	duk_minimal_snprintf(buffer, 9, "foo: %s", "bar");
	dump_buffer();

	/* sprintf() binding, uses SIZE_MAX internally. */
	init_buffer();
	duk_minimal_sprintf(buffer, "unbounded print %s", "foo");
	dump_buffer();

	/* Pointer formatting; non-NULL and NULL. */
	init_buffer();
	duk_minimal_snprintf(buffer, sizeof(buffer), "%p %p", (void *) NULL, (void *) 0xdeadbeef);
	dump_buffer();

	/* Pointer parsing, non-NULL (32-bit) pointer. */
	voidptr = (void *) 123;
	ret = duk_minimal_sscanf("0xdeadbeef", "%p", &voidptr);
	printf("ret=%d, void pointer: %p\n", ret, voidptr);

	/* Pointer parsing, NULL (32-bit) pointer. */
	voidptr = (void *) 123;
	ret = duk_minimal_sscanf("0x00000000", "%p", &voidptr);
	printf("ret=%d, void pointer: %p\n", ret, voidptr);

	/* Pointer parsing, non-NULL (32-bit) pointer but garbage follows. */
	voidptr = (void *) 123;
	ret = duk_minimal_sscanf("0xdeadbeefx", "%p", &voidptr);
	printf("ret=%d, void pointer: %p\n", ret, voidptr);

	/* Fixed width test over a range of widths. */
	for (i = 0; i <= 9; i++) {
		char fmtbuf[16];

		printf("--- pos/neg fixed width test, i=%d\n", i);

		/* %0<i>d. %00d makes no sense, but tested anyway. */
		memset((void *) fmtbuf, 0, sizeof(fmtbuf));
		fmtbuf[0] = (char) '%';
		fmtbuf[1] = (char) '0';
		fmtbuf[2] = (char) ('0' + i);
		fmtbuf[3] = 'd';
		init_buffer();
		duk_minimal_sprintf(buffer, (const char *) fmtbuf, 321);
		dump_buffer();
		init_buffer();
		duk_minimal_sprintf(buffer, (const char *) fmtbuf, -321);
		dump_buffer();
		printf("  ==> printf: |");
		printf((const char *) fmtbuf, 321);
		printf("| |");
		printf((const char *) fmtbuf, -321);
		printf("|\n");

		/* %<i>d. */
		memset((void *) fmtbuf, 0, sizeof(fmtbuf));
		fmtbuf[0] = (char) '%';
		fmtbuf[1] = (char) ('0' + i);
		fmtbuf[2] = 'd';
		init_buffer();
		duk_minimal_sprintf(buffer, (const char *) fmtbuf, 321);
		dump_buffer();
		init_buffer();
		duk_minimal_sprintf(buffer, (const char *) fmtbuf, -321);
		dump_buffer();
		printf("  ==> printf: |");
		printf((const char *) fmtbuf, 321);
		printf("| |");
		printf((const char *) fmtbuf, -321);
		printf("|\n");
	}

	return 0;
}
Exemplo n.º 7
0
int
keepalived_free(void *buffer, char *file, char *function, int line)
{
	int i = 0;
	void *buf = buffer;

	/* If nullpointer remember */
	if (buffer == NULL) {
		i = number_alloc_list++;

		assert(number_alloc_list < MAX_ALLOC_LIST);

		alloc_list[i].ptr = buffer;
		alloc_list[i].size = 0;
		alloc_list[i].file = file;
		alloc_list[i].func = function;
		alloc_list[i].line = line;
		alloc_list[i].type = 2;
		fprintf(log_op, "free NULL in %s, %3d, %s\n", file,
		       line, function);

		__set_bit(MEM_ERR_DETECT_BIT, &debug);	/* Memory Error detect */

		return n;
	}

	while (i < number_alloc_list) {
		if (alloc_list[i].type == 9 && alloc_list[i].ptr == buf) {
			if (*((long *) ((char *) alloc_list[i].ptr + alloc_list[i].size)) == alloc_list[i].csum) {
				alloc_list[i].type = 0;	/* Release */
				mem_allocated -= alloc_list[i].size - sizeof(long);
			} else {
				alloc_list[i].type = 1;	/* Overrun */
				fprintf(log_op, "free corrupt, buffer overrun [%3d:%3d], %p, %4zu at %s, %3d, %s\n",
				       i, number_alloc_list,
				       buf, alloc_list[i].size, file,
				       line, function);
				dump_buffer(alloc_list[i].ptr,
					    alloc_list[i].size + sizeof (long), log_op);
				fprintf(log_op, "Check_sum\n");
				dump_buffer((char *) &alloc_list[i].csum,
					    sizeof(long), log_op);

				__set_bit(MEM_ERR_DETECT_BIT, &debug);
			}
			break;
		}
		i++;
	}

	/*  Not found */
	if (i == number_alloc_list) {
		fprintf(log_op, "Free ERROR %p not found\n", buffer);
		number_alloc_list++;

		assert(number_alloc_list < MAX_ALLOC_LIST);

		alloc_list[i].ptr = buf;
		alloc_list[i].size = 0;
		alloc_list[i].file = file;
		alloc_list[i].func = function;
		alloc_list[i].line = line;
		alloc_list[i].type = 4;
		__set_bit(MEM_ERR_DETECT_BIT, &debug);

		return n;
	}

	fprintf(log_op, "free  [%3d:%3d], %p, %4zu at %s, %3d, %s\n",
	       i, number_alloc_list, buf,
	       alloc_list[i].size, file, line, function);
#ifdef _MEM_CHECK_LOG_
	if (__test_bit(MEM_CHECK_LOG_BIT, &debug))
		log_message(LOG_INFO, "free  [%3d:%3d], %p, %4zu at %s, %3d, %s\n",
		       i, number_alloc_list, buf,
		       alloc_list[i].size, file, line, function);
#endif

	if (buffer != NULL)
		free(buffer);

	free_list[f].file = file;
	free_list[f].line = line;
	free_list[f].func = function;
	free_list[f].ptr = buffer;
	free_list[f].type = 8;
	free_list[f].csum = i;	/* Using this field for row id */

	f++;
	f &= 255;
	n--;

	return n;
}
Exemplo n.º 8
0
static int read_f(int argc, char **argv)
{
    struct timeval t1, t2;
    int Cflag = 0, pflag = 0, qflag = 0, vflag = 0;
    int Pflag = 0, sflag = 0, lflag = 0, bflag = 0;
    int c, cnt;
    char *buf;
    int64_t offset;
    int count;
    /* Some compilers get confused and warn if this is not initialized.  */
    int total = 0;
    int pattern = 0, pattern_offset = 0, pattern_count = 0;

    while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != EOF) {
        switch (c) {
        case 'b':
            bflag = 1;
            break;
        case 'C':
            Cflag = 1;
            break;
        case 'l':
            lflag = 1;
            pattern_count = cvtnum(optarg);
            if (pattern_count < 0) {
                printf("non-numeric length argument -- %s\n", optarg);
                return 0;
            }
            break;
        case 'p':
            pflag = 1;
            break;
        case 'P':
            Pflag = 1;
            pattern = parse_pattern(optarg);
            if (pattern < 0) {
                return 0;
            }
            break;
        case 'q':
            qflag = 1;
            break;
        case 's':
            sflag = 1;
            pattern_offset = cvtnum(optarg);
            if (pattern_offset < 0) {
                printf("non-numeric length argument -- %s\n", optarg);
                return 0;
            }
            break;
        case 'v':
            vflag = 1;
            break;
        default:
            return command_usage(&read_cmd);
        }
    }

    if (optind != argc - 2) {
        return command_usage(&read_cmd);
    }

    if (bflag && pflag) {
        printf("-b and -p cannot be specified at the same time\n");
        return 0;
    }

    offset = cvtnum(argv[optind]);
    if (offset < 0) {
        printf("non-numeric length argument -- %s\n", argv[optind]);
        return 0;
    }

    optind++;
    count = cvtnum(argv[optind]);
    if (count < 0) {
        printf("non-numeric length argument -- %s\n", argv[optind]);
        return 0;
    }

    if (!Pflag && (lflag || sflag)) {
        return command_usage(&read_cmd);
    }

    if (!lflag) {
        pattern_count = count - pattern_offset;
    }

    if ((pattern_count < 0) || (pattern_count + pattern_offset > count))  {
        printf("pattern verification range exceeds end of read data\n");
        return 0;
    }

    if (!pflag) {
        if (offset & 0x1ff) {
            printf("offset %" PRId64 " is not sector aligned\n",
                   offset);
            return 0;
        }
        if (count & 0x1ff) {
            printf("count %d is not sector aligned\n",
                   count);
            return 0;
        }
    }

    buf = qemu_io_alloc(count, 0xab);

    gettimeofday(&t1, NULL);
    if (pflag) {
        cnt = do_pread(buf, offset, count, &total);
    } else if (bflag) {
        cnt = do_load_vmstate(buf, offset, count, &total);
    } else {
        cnt = do_read(buf, offset, count, &total);
    }
    gettimeofday(&t2, NULL);

    if (cnt < 0) {
        printf("read failed: %s\n", strerror(-cnt));
        goto out;
    }

    if (Pflag) {
        void *cmp_buf = g_malloc(pattern_count);
        memset(cmp_buf, pattern, pattern_count);
        if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {
            printf("Pattern verification failed at offset %"
                   PRId64 ", %d bytes\n",
                   offset + pattern_offset, pattern_count);
        }
        g_free(cmp_buf);
    }

    if (qflag) {
        goto out;
    }

    if (vflag) {
        dump_buffer(buf, offset, count);
    }

    /* Finally, report back -- -C gives a parsable format */
    t2 = tsub(t2, t1);
    print_report("read", &t2, offset, count, total, cnt, Cflag);

out:
    qemu_io_free(buf);

    return 0;
}
static int authenticated_data_read(char *buff, int len, int addr)
{
	int data_cnt = 0; /* in bytes */
	int sec_addr = addr; /* half sector address to read from */
	int ret = 0;
	struct rpmb_data_frame data_packet;
	unsigned char *read_buff = NULL;
	struct rpmb_data_frame *read_data_packet;
	unsigned short result;
	int num_half_sec;
	int retries = RPMB_ACCESS_RETRY;

#if DEBUG
	unsigned char *ptr_auth_read_data = (unsigned char *)&data_packet;
#endif

	/* 0x20000 = 128K = RPMB size */
	if (((sec_addr << 8) + len) > 0x20000) {
		pr_err("authenticated_data_read:"
						"cannot read past end of RPMB\n");
		return -EOTHER;
	}

#if DEBUG
	pr_info("%s: buff: %p, len: %d, addr: %x\n",
				__func__, buff, len, addr);
#endif

	num_half_sec = (len % PAYLOAD_SIZE) ?
						((len / PAYLOAD_SIZE) + 1) :
						(len / PAYLOAD_SIZE);

	/* Allocate memory for read_buff */
	read_buff = kmalloc(RPMB_DATA_FRAME_SIZE, GFP_KERNEL);

	do {
read_retry:
		/* Format Authenticated Read Data Packet */
		format_auth_read_data_packet(&data_packet, sec_addr);

		/*
		 * Reverse Data Packet to make it MSB first byte order,
		 * as expected by RPMB
		 */
		reverse_array((unsigned char *)&data_packet,
					sizeof(struct rpmb_data_frame));

#if DEBUG
		pr_info("%s: Read Data Packet WRITE\n", __func__);
		dump_buffer((char *)ptr_auth_read_data, RPMB_DATA_FRAME_SIZE);
#endif

		/* Write the Data Packet to RPMB */
		ret = block_write(RPMB_DEV_NODE_PATH,
				(char *)&data_packet, /* Data buffer */
				RPMB_DATA_FRAME_SIZE, /* Size of data packet */
				0x0); /* special flags if any */
		if (ret < 0) {
			pr_err("Write Data Packet failed: %d\n", ret);
			ret = -EOTHER;
			goto out;
		}

		memset(&read_buff[0], 0x0, RPMB_DATA_FRAME_SIZE);

		/* Read the data packet from RPMB */
		ret = block_read(RPMB_DEV_NODE_PATH,
				&read_buff[0], /* Data buffer */
				RPMB_DATA_FRAME_SIZE); /* Size of data packet */
		if (ret < 0) {
			pr_err("Read Data Packet failed: %d\n", ret);
			ret = -EOTHER;
			goto out;
		}

#if DEBUG
		pr_info("%s: Read Data Packet READ:\n", __func__);
		dump_buffer((char *)read_buff, RPMB_DATA_FRAME_SIZE);
#endif

		/* read_buff is returned in MSB First Byte Order, reverse it */
		reverse_array(read_buff, RPMB_DATA_FRAME_SIZE);

		read_data_packet = (struct rpmb_data_frame *)read_buff;

#if DEBUG
		pr_info("Result Register Value: 0x%x \r\n",
				read_data_packet->result);
#endif

		/* Check if Authentication Key is programmed & return if NOT */
		result = read_data_packet->result;
		if (result == RESULT_AUTH_KEY_NOT_PROGRAMMED) {
			pr_info("Authentication Key NOT programmed; result: 0x%x\n",
					result);
			ret = -EKEYNOTPROG;
			goto out;
		}

		/*
		* Retry on GENERAL FAILURE
		*
		* "Short Story" on why this retry mechanism is needed:
		* On "Micron eMMC parts", when RPMB transaction session is in
		* progress, if a new (read/write) request is issued to a
		* NON-RPMB (user data) partition on the eMMC, and then we
		* continue the previous RPMB access transaction, the RPMB
		* access returns GENERAL FAILURE.
		*
		* Below log snapshot will help explain this better:
		* -------> START RPMB TRANSACTION <-- (session 1)
		*		--> RPMB CMD6 - Switch to RPMB partition
		*		--> RPMB CMD23 - Set BLK_CNT
		*		--> RPMB CMD25 - Issue a Mult Blk Write
		*		--> RPMB CMD13 - Issue Status CMD and
		*			check Write completion
		* -------> RPMB TRANSACTION ABORTED BY NON-RPMB ACCESS
		*		--> NON-RPMB CMD6 - Switch to Userdata partition
		*		--> NON-RPMB CMD23 - Set BLK_CNT
		*		--> NON-RPMB CMD25 - Issue Mutl Blk Write
		*		--> NON-RPMB CMD12 - Issue Status CMD and
		*			check completion
		* -------> SWITCH BACK TO RPMB PARTITION <--
		*				(Continue session 1)
		*		--> RPMB CMD6 - Switch back to RPMB partition
		*		--> RPMB CMD23 - Set BLK_CNT
		*		--> RPMB CMD18 - Issue a Mult Blk Read
		* The RPMB device returns GENERAL FAILURE in the Read data
		* Packet.
		*
		* When we get into this scenario (GENERAL FAILURE), we simply
		* retry for 20 times and hope that we succeed atleast once.
		*
		* Refer to Sec: 7.6.16.4 in JESD84-A441.pdf on why this
		* needs to be done here.
		*/
		/* General Failure, retry */
		if (result == RESULT_GENERAL_FAILURE) {
			pr_err("RPMB Read Data General Error. Retrying...\n");
			if (--retries) {
				pr_err("Retry count: %d\n", retries);
				goto read_retry;
			} else { /* Retries exhausted, return error */
				pr_err("Retried %d times. No success."
						"Returning error to caller\n",
						RPMB_ACCESS_RETRY);
				ret = -EGENERR;
				goto out;
			}
		}

		/* Authenticate the read data packet */
		memset(mac_payload_buff, 0, PAYLOAD_SIZE_FOR_MAC);
		memset(key_mac_buff, 0, KEY_MAC_SIZE);
		memcpy(mac_payload_buff, (unsigned char *)read_data_packet,
				PAYLOAD_SIZE_FOR_MAC);
		reverse_array(mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);

#if DEBUG
		pr_info("%s: Payload for HMA-SHA256 calculation\n", __func__);
		dump_buffer((char *)mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);
#endif

		/* Call HMAC-SHA256 function to compute MAC */
		hmac_sha256(magic_key, KEY_MAC_SIZE,
				mac_payload_buff, PAYLOAD_SIZE_FOR_MAC,
				key_mac_buff, KEY_MAC_SIZE);

#if DEBUG
		pr_info("%s: HMAC-SHA256 value:\n", __func__);
		dump_buffer((char *)key_mac_buff, KEY_MAC_SIZE);
#endif

		/* Compare computed MAC against MAC value in the data frame */
		reverse_array(key_mac_buff, KEY_MAC_SIZE);
		ret = memcmp(key_mac_buff, read_data_packet->key_mac,
						KEY_MAC_SIZE);
		if (ret) {
			pr_err("%s: HMAC-SHA256 check failed. Data could be invalid",
					__func__);
			ret = -EDATACHKFAIL;
			goto out;
		}

		/* Check for other errors */
		if (read_data_packet->req_resp_code ==
			RESPONSE_TYPE_AUTH_DATA_READ) {

			if (result == RESULT_ADDRESS_FAILURE) {
				pr_err("Write address Error\n");
				ret = -EADDRFAIL;
				goto out;
			}

			if (result == RESULT_AUTHENTICATION_FAILURE) {
				pr_err("Read Data Authentication Failure\n");
				ret = -EAUTHFAIL;
				goto out;
			}

			if (result == RESULT_READ_FAILURE) {
				pr_err("Read Data Error\n");
				ret = -EREADFAIL;
				goto out;
			}
		} else {
			pr_err("Read Data- Wrong response type\n");
			ret = -EOTHER;
			goto out;
		}

		/* Copy data to user buffer */
		if (--num_half_sec) /* Not the last half-sector */
			memcpy(buff + data_cnt, read_data_packet->data,
					PAYLOAD_SIZE);
		else /* Last half sector */
			memcpy(buff + data_cnt, read_data_packet->data, len);

		len -= PAYLOAD_SIZE;
		data_cnt += PAYLOAD_SIZE;
		sec_addr++;
	} while (num_half_sec);

out:
	kfree(read_buff);
	return ret;
}
Exemplo n.º 10
0
int
mread_f(
	int		argc,
	char		**argv)
{
	off64_t		offset, tmp, dumpoffset, printoffset;
	ssize_t		length;
	size_t		dumplen, cnt = 0;
	char		*bp;
	void		*start;
	int		dump = 0, rflag = 0, c;
	size_t		blocksize, sectsize;

	while ((c = getopt(argc, argv, "frv")) != EOF) {
		switch (c) {
		case 'f':
			dump = 2;	/* file offset dump */
			break;
		case 'r':
			rflag = 1;	/* read in reverse */
			break;
		case 'v':
			dump = 1;	/* mapping offset dump */
			break;
		default:
			return command_usage(&mread_cmd);
		}
	}

	if (optind == argc) {
		offset = mapping->offset;
		length = mapping->length;
	} else if (optind == argc - 2) {
		init_cvtnum(&blocksize, &sectsize);
		offset = cvtnum(blocksize, sectsize, argv[optind]);
		if (offset < 0) {
			printf(_("non-numeric offset argument -- %s\n"),
				argv[optind]);
			return 0;
		}
		optind++;
		length = cvtnum(blocksize, sectsize, argv[optind]);
		if (length < 0) {
			printf(_("non-numeric length argument -- %s\n"),
				argv[optind]);
			return 0;
		}
	} else {
		return command_usage(&mread_cmd);
	}

	start = check_mapping_range(mapping, offset, length, 0);
	if (!start)
		return 0;
	dumpoffset = offset - mapping->offset;
	if (dump == 2)
		printoffset = offset;
	else
		printoffset = dumpoffset;

	if (alloc_buffer(pagesize, 0, 0) < 0)
		return 0;
	bp = (char *)buffer;

	dumplen = length % pagesize;
	if (!dumplen)
		dumplen = pagesize;

	if (rflag) {
		for (tmp = length - 1, c = 0; tmp >= 0; tmp--, c = 1) {
			*bp = *(((char *)mapping->addr) + dumpoffset + tmp);
			cnt++;
			if (c && cnt == dumplen) {
				if (dump) {
					dump_buffer(printoffset, dumplen);
					printoffset += dumplen;
				}
				bp = (char *)buffer;
				dumplen = pagesize;
				cnt = 0;
			} else {
				bp++;
			}
		}
	} else {
		for (tmp = 0, c = 0; tmp < length; tmp++, c = 1) {
			*bp = *(((char *)mapping->addr) + dumpoffset + tmp);
			cnt++;
			if (c && cnt == dumplen) {
				if (dump)
					dump_buffer(printoffset + tmp -
						(dumplen - 1), dumplen);
				bp = (char *)buffer;
				dumplen = pagesize;
				cnt = 0;
			} else {
				bp++;
			}
		}
	}
	return 0;
}
static int authenticated_data_write(const char *data, int bytes, int addr)
{
	int ret = 0;
	struct rpmb_data_frame data_packet;
	unsigned char *read_buff;
	struct rpmb_data_frame *read_data_packet;
	unsigned short result;
	int counter_val;
	int blkcnt; /* half sector (256B) count */
	int data_size = bytes;
	int retries = RPMB_ACCESS_RETRY;

#if DEBUG
	unsigned char *ptr_auth_write_data = (unsigned char *)&data_packet;
	unsigned char *ptr_result_reg = (unsigned char *)&data_packet;
#endif

	/* If (start + (blkcnt * 512)) > rpmb_size, return error */
	if (((addr << 8) + bytes) > (128*1024)) {
		pr_err("Cannot write past the RPMB paritition size\n");
		return -EOTHER;
	}

	blkcnt = (bytes % PAYLOAD_SIZE) ?
				((bytes / PAYLOAD_SIZE) + 1) :
				(bytes / PAYLOAD_SIZE);

#if DEBUG
	pr_info("data: %p, bytes: %d, blkcnt: %d, addr: %x\n",
			data, bytes, blkcnt, addr);
#endif

	/* alloc memory for read_buff */
	read_buff = kmalloc(RPMB_DATA_FRAME_SIZE, GFP_KERNEL);

	do {
		/* Get counter value */
		counter_val = read_counter_value();
		if (counter_val < 0) {
			pr_err("Counter value read failed\n");
			ret = -ECOUNTERERR;
			goto out;
		}

write_retry:
		/* Format Authenticated Write Data Packet */
		if (blkcnt == 1) /* last half sector data */
			format_auth_write_data_packet(&data_packet, data,
					data_size, counter_val, addr);
		else /* Not the last half sector data */
			format_auth_write_data_packet(&data_packet, data,
					PAYLOAD_SIZE, counter_val, addr);

		/*
		 * Reverse Data Packet to MSB first byte order as
		 * expected by RPMB
		 */
		reverse_array((unsigned char *)&data_packet,
					sizeof(struct rpmb_data_frame));

#if DEBUG
		pr_info("%s: Write Data Packet WRITE\n", __func__);
		dump_buffer((char *)ptr_auth_write_data, RPMB_DATA_FRAME_SIZE);
#endif

		/* Write the Data Packet to RPMB */
		ret = block_write(RPMB_DEV_NODE_PATH,
				(char *)&data_packet, /* Data buffer */
				RPMB_DATA_FRAME_SIZE, /* Size of data packet */
				REQ_META); /* special flags if any */
		if (ret < 0) {
			pr_err("Write Data Packet failed: %d\n", ret);
			ret = -EOTHER;
			goto out;
		}

		/* Format Read Result Register Data Packet */
		format_read_result_reg_data_packet(&data_packet);

		/* Reverse Data Packet to MSB first byte order */
		reverse_array((unsigned char *)&data_packet,
					sizeof(struct rpmb_data_frame));

#if DEBUG
		pr_info("%s: read_result_reg WRITE\n", __func__);
		dump_buffer((char *)ptr_result_reg, RPMB_DATA_FRAME_SIZE);
#endif

		/* Write the Read Result Register data packet to RPMB */
		ret = block_write(RPMB_DEV_NODE_PATH,
				(char *)&data_packet, /* Data buffer */
				RPMB_DATA_FRAME_SIZE, /* Size of data packet */
				0x0); /* special flags if any */
		if (ret < 0) {
			pr_err("Write Result Resgister Data"
					"Packet failed: %d\n", ret);
			ret = -EOTHER;
			goto out;
		}

		/* Read the Read Result Register data packet from RPMB */
		ret = block_read(RPMB_DEV_NODE_PATH,
				&read_buff[0], /* Data buffer */
				RPMB_DATA_FRAME_SIZE); /* Size of data packet */
		if (ret < 0) {
			pr_err("Read Result Resgister Data"
					"Packet failed: %d\n", ret);
			ret = -EOTHER;
			goto out;
		}

#if DEBUG
		pr_info("%s: Result Reg Data Packet READ:\n", __func__);
		dump_buffer((char *)read_buff, RPMB_DATA_FRAME_SIZE);
#endif

		/* read_buff is returned in MSB First Byte Order, reverse it */
		reverse_array(read_buff, RPMB_DATA_FRAME_SIZE);

		read_data_packet = (struct rpmb_data_frame *)read_buff;

#if DEBUG
		pr_info("Result Register Value: 0x%x \r\n",
					read_data_packet->result);
#endif

		/* Check if Authentication is programmed and return if NOT */
		result = read_data_packet->result;
		if (result == RESULT_AUTH_KEY_NOT_PROGRAMMED) {
			pr_err("Authentication Key NOT programmed; result: 0x%x\n",
					result);
			ret = -EKEYNOTPROG;
			goto out;
		}

		/* Retry on GENERAL FAILURE */
		if (result == RESULT_GENERAL_FAILURE) {
			pr_err("Write Data General Failure. Retrying....\n");
			if (--retries) {
				pr_err("Retry count: %d\n", retries);
				goto write_retry;
			} else {
				pr_err("Retried %d times. No success."
						"Returning error to caller\n",
						RPMB_ACCESS_RETRY);
				ret = -EGENERR;
				goto out;
			}
		}

		/* Authenticate Counter value data packet */
		memset(mac_payload_buff, 0, PAYLOAD_SIZE_FOR_MAC);
		memset(key_mac_buff, 0, KEY_MAC_SIZE);
		memcpy(mac_payload_buff, (unsigned char *)read_data_packet,
				PAYLOAD_SIZE_FOR_MAC);
		reverse_array(mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);

#if DEBUG
		pr_info("%s: Payload for HMA-SHA256 calculation\n", __func__);
		dump_buffer((char *)mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);
#endif

		/* Call HMAC-SHA256 function to compute MAC */
		hmac_sha256(magic_key, KEY_MAC_SIZE,
				mac_payload_buff, PAYLOAD_SIZE_FOR_MAC,
				key_mac_buff, KEY_MAC_SIZE);

#if DEBUG
		pr_info("%s: HMAC-SHA256 value:\n", __func__);
		dump_buffer((char *)key_mac_buff, KEY_MAC_SIZE);
#endif

		/* Compare the computed MAC against MAC in data frame */
		reverse_array(key_mac_buff, KEY_MAC_SIZE);
		ret = memcmp(key_mac_buff, read_data_packet->key_mac,
						KEY_MAC_SIZE);
		if (ret) {
			pr_err("%s: HMAC-SHA256 check failed. Data may be invalid",
					__func__);
			ret = -EDATACHKFAIL;
			goto out;
		}

		/* Check for other write errors */
		if (read_data_packet->req_resp_code ==
			RESPONSE_TYPE_AUTH_DATA_WRITE) {

			if (result & RESULT_COUNTER_EXPIRED_FLAG) {
				pr_err("Write Counter expired\n");
				ret = -ECOUNTERERR;
				goto out;
			} else {
				if (result == RESULT_ADDRESS_FAILURE) {
					pr_err("Write address Error\n");
					ret = -EADDRFAIL;
					goto out;
				}

				if (result == RESULT_AUTHENTICATION_FAILURE) {
					pr_err("Write Data Authentication Failure\n");
					ret = -EAUTHFAIL;
					goto out;
				}

				if (result == RESULT_COUNTER_FAILURE) {
					pr_err("Write Counter Mismatch Error\n");
					ret = -ECOUNTERERR;
					goto out;
				}

				if (result == RESULT_WRITE_FAILURE) {
					pr_err("Write Data Error\n");
					ret = -EWRITEFAIL;
					goto out;
				}
			}
		} else {
			pr_err("Write Data- Wrong response type\n");
			ret = -EOTHER;
			goto out;
		}

		data += PAYLOAD_SIZE;
		data_size -= PAYLOAD_SIZE;
		addr++;
		blkcnt--;
	} while (blkcnt);

out:
	kfree(read_buff);
	return ret;
}
static int read_counter_value(void)
{
	int ret = 0;
	struct rpmb_data_frame data_packet;
	unsigned char *read_buff;
	struct rpmb_data_frame *read_data_packet;
	unsigned short result;
	unsigned int counter;
	int retries = RPMB_ACCESS_RETRY;

#if DEBUG
	unsigned char *ptr_counter_val = (unsigned char *)&data_packet;
#endif

	/* Alloc memory for read_buff */
	read_buff = kmalloc(RPMB_DATA_FRAME_SIZE, GFP_KERNEL);

counter_retry:
	/* Format the Read counter value Data Packet */
	format_read_counter_val_data_packet(&data_packet);

	/* Reverse Data Packet to MSB first byte order as expected by RPMB */
	reverse_array((unsigned char *)&data_packet,
				sizeof(struct rpmb_data_frame));

#if DEBUG
	pr_info("%s: Counter Value Data Packet WRITE\n", __func__);
	dump_buffer((char *)ptr_counter_val, RPMB_DATA_FRAME_SIZE);
#endif

	/* Write the Read Counter Value Data Packet to RPMB */
	ret = block_write(RPMB_DEV_NODE_PATH,
				(char *)&data_packet, /* Data buffer */
				RPMB_DATA_FRAME_SIZE, /* Size of data packet */
				0x0); /* special flags if any */
	if (ret < 0) {
		pr_err("Write Counter Value Data Packet failed: %d\n", ret);
		ret = -EOTHER;
		goto out;
	}

	/* Read the Counter Value data packet from RPMB */
	ret = block_read(RPMB_DEV_NODE_PATH,
				&read_buff[0], /* Data buffer */
				RPMB_DATA_FRAME_SIZE); /* Size of data packet */
	if (ret < 0) {
		pr_err("Read Counter Value Data Packet failed: %d\n", ret);
		ret = -EOTHER;
		goto out;
	}

#if DEBUG
	pr_info("%s: Counter Value Data Packet READ:\n", __func__);
	dump_buffer((char *)read_buff, RPMB_DATA_FRAME_SIZE);
#endif

	/* read_buff is returned in MSB First Byte Order, reverse it */
	reverse_array(read_buff, RPMB_DATA_FRAME_SIZE);

	read_data_packet = (struct rpmb_data_frame *)read_buff;

	result = read_data_packet->result;
	counter = read_data_packet->write_counter;

#if DEBUG
	pr_info("Result Register Value: 0x%x \r\n", result);
	pr_info("Counter Value: 0x%x \r\n", counter);
#endif

	/* Check if Authentication is programmed up front and return if NOT */
	if (result == RESULT_AUTH_KEY_NOT_PROGRAMMED) {
		pr_err("Authentication Key NOT programmed; result: 0x%x\n",
				result);
		ret = -EKEYNOTPROG;
		goto out;
	}

	/* Retry on GENERAL FAILURE */
	if (result == RESULT_GENERAL_FAILURE) {
		pr_err("Read Counter Value- GENERAL FAILURE. Retrying....\n");
		if (--retries) {
			pr_err("%s: Retry count: %d\n", __func__, retries);
			goto counter_retry;
		} else {
			pr_err("%s: Retried %d times. No success."
					"Returning error to caller\n",
					__func__, RPMB_ACCESS_RETRY);
			ret = -EGENERR;
			goto out;
		}
	}

	/* Authenticate Counter value data packet */
	memset(mac_payload_buff, 0, PAYLOAD_SIZE_FOR_MAC);
	memset(key_mac_buff, 0, KEY_MAC_SIZE);
	memcpy(mac_payload_buff, (unsigned char *)read_data_packet,
			PAYLOAD_SIZE_FOR_MAC);
	reverse_array(mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);

#if DEBUG
	pr_info("%s: Payload for HMA-SHA256 calculation\n", __func__);
	dump_buffer((char *)mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);
#endif

	/* Call HMAC-SHA256 function to compute MAC */
	hmac_sha256(magic_key, KEY_MAC_SIZE,
			mac_payload_buff, PAYLOAD_SIZE_FOR_MAC,
			key_mac_buff, KEY_MAC_SIZE);

#if DEBUG
	pr_info("%s: HMAC-SHA256 value:\n", __func__);
	dump_buffer((char *)key_mac_buff, KEY_MAC_SIZE);
#endif

	/* Compare the computed MAC against the MAC value in the data frame */
	reverse_array(key_mac_buff, KEY_MAC_SIZE);
	ret = memcmp(key_mac_buff, read_data_packet->key_mac, KEY_MAC_SIZE);
	if (ret) {
		pr_err("%s: HMAC-SHA256 check failed. Data may be invalid",
				__func__);
		ret = -EDATACHKFAIL;
		goto out;
	}

	/* Check for Read Counter Errors */
	if (read_data_packet->req_resp_code ==
		RESPONSE_TYPE_READ_WRITE_COUNTER) {

		if (result & RESULT_COUNTER_EXPIRED_FLAG) {
			pr_err("Write Counter expired\n");
			ret = -ECOUNTERERR;
			goto out;
		} else {
			if (result == RESULT_READ_FAILURE) {
				pr_err("Read Counter Value- READ ERROR\n");
				ret = -EREADFAIL;
				goto out;
			}
		}
	} else {
		pr_err("Read Counter Value- Wrong response type\n");
		ret = -EOTHER;
		goto out;
	}

	kfree(read_buff);
	return counter;
out:
	kfree(read_buff);
	return ret;
}
static void format_auth_write_data_packet(
		struct rpmb_data_frame *auth_write_data,
		const char *data, /* Data/Payload */
		int size, /* Size of data to be written in bytes */
		unsigned int write_counter, /* Current Write Counter Value */
		unsigned short address /* Start address of access */)
{
	/* memset to zero before start */
	memset(auth_write_data, 0, sizeof(struct rpmb_data_frame));

#if DEBUG
	pr_info("%s: Copying %d bytes to RPMB data frame\n",
				__func__, size);
#endif

	/* Next copy the Payload */
	memcpy(auth_write_data->data, data, size);

	/* Next copy the Write Counter */
	auth_write_data->write_counter = write_counter;

	/* Copy the Start Address */
	auth_write_data->address = address;

	/* We always only write 1 blk */
	auth_write_data->blk_count = 1;

	/* Set Request type to indicate Write Request */
	auth_write_data->req_resp_code = REQUEST_TYPE_AUTH_DATA_WRITE;

	/* Next Calculate HMAC-SHA256 on the RPMB data frame [283:0] bytes */
	memset(mac_payload_buff, 0, PAYLOAD_SIZE_FOR_MAC);
	memset(key_mac_buff, 0, KEY_MAC_SIZE);
	memcpy(mac_payload_buff, (unsigned char *)auth_write_data,
				PAYLOAD_SIZE_FOR_MAC);
	reverse_array(mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);

#if DEBUG
	pr_info("%s: Payload for HMA-SHA256 calculation\n", __func__);
	dump_buffer((char *)mac_payload_buff, PAYLOAD_SIZE_FOR_MAC);
#endif

	/* Call HMAC-SHA256 function to compute MAC */
	hmac_sha256(magic_key, KEY_MAC_SIZE,
			mac_payload_buff, PAYLOAD_SIZE_FOR_MAC,
			key_mac_buff, KEY_MAC_SIZE);

#if DEBUG
	pr_info("%s: HMAC-SHA256 value:\n", __func__);
	dump_buffer((char *)key_mac_buff, KEY_MAC_SIZE);
#endif

	/*
	 * Reverse and set the MAC value in MAC field of Data Frame.
	 *
	 * NOTE: Reversing is needed here because we computed MAC on BE Data
	 * Frame and we need to reverse the MAC here which will be converted
	 * to the correct Byte Order before write() is called in the calling
	 * function.
	 */
	reverse_array(key_mac_buff, KEY_MAC_SIZE);
	memcpy(auth_write_data->key_mac, key_mac_buff, KEY_MAC_SIZE);

	return;
}
Exemplo n.º 14
0
static int
ssif_polled_request(struct ipmi_softc *sc, struct ipmi_request *req)
{
	u_char ssif_buf[SMBUS_DATA_SIZE];
	device_t dev = sc->ipmi_dev;
	device_t smbus = sc->ipmi_ssif_smbus;
	u_char *cp, block, count, offset;
	size_t len;
	int error;

	/* Acquire the bus while we send the request. */
	if (smbus_request_bus(smbus, dev, SMB_WAIT) != 0)
		return (0);

	/*
	 * First, send out the request.  Begin by filling out the first
	 * packet which includes the NetFn/LUN and command.
	 */
	ssif_buf[0] = req->ir_addr;
	ssif_buf[1] = req->ir_command;
	if (req->ir_requestlen > 0)
		bcopy(req->ir_request, &ssif_buf[2],
		    min(req->ir_requestlen, SMBUS_DATA_SIZE - 2));

	/* Small requests are sent with a single command. */
	if (req->ir_requestlen <= 30) {
#ifdef SSIF_DEBUG
		dump_buffer(dev, "WRITE_SINGLE", ssif_buf,
		    req->ir_requestlen + 2);
#endif
		error = smbus_error(smbus_bwrite(smbus,
			sc->ipmi_ssif_smbus_address, SMBUS_WRITE_SINGLE,
			req->ir_requestlen + 2, ssif_buf));
		if (error) {
#ifdef SSIF_ERROR_DEBUG
			device_printf(dev, "SSIF: WRITE_SINGLE error %d\n",
			    error);
#endif
			goto fail;
		}
	} else {
		/* Longer requests are sent out in 32-byte messages. */
#ifdef SSIF_DEBUG
		dump_buffer(dev, "WRITE_START", ssif_buf, SMBUS_DATA_SIZE);
#endif
		error = smbus_error(smbus_bwrite(smbus,
			sc->ipmi_ssif_smbus_address, SMBUS_WRITE_START,
			SMBUS_DATA_SIZE, ssif_buf));
		if (error) {
#ifdef SSIF_ERROR_DEBUG
			device_printf(dev, "SSIF: WRITE_START error %d\n",
			    error);
#endif
			goto fail;
		}

		len = req->ir_requestlen - (SMBUS_DATA_SIZE - 2);
		cp = req->ir_request + (SMBUS_DATA_SIZE - 2);
		while (len > 0) {
#ifdef SSIF_DEBUG
			dump_buffer(dev, "WRITE_CONT", cp,
			    min(len, SMBUS_DATA_SIZE));
#endif
			error = smbus_error(smbus_bwrite(smbus,
			    sc->ipmi_ssif_smbus_address, SMBUS_WRITE_CONT,
			    min(len, SMBUS_DATA_SIZE), cp));
			if (error) {
#ifdef SSIF_ERROR_DEBUG
				device_printf(dev, "SSIF: WRITE_CONT error %d\n",
				    error);
#endif
				goto fail;
			}
			cp += SMBUS_DATA_SIZE;
			len -= SMBUS_DATA_SIZE;
		}

		/*
		 * The final WRITE_CONT transaction has to have a non-zero
		 * length that is also not SMBUS_DATA_SIZE.  If our last
		 * WRITE_CONT transaction in the loop sent SMBUS_DATA_SIZE
		 * bytes, then len will be 0, and we send an extra 0x00 byte
		 * to terminate the transaction.
		 */
		if (len == 0) {
			char c = 0;

#ifdef SSIF_DEBUG
			dump_buffer(dev, "WRITE_CONT", &c, 1);
#endif
			error = smbus_error(smbus_bwrite(smbus,
				sc->ipmi_ssif_smbus_address, SMBUS_WRITE_CONT,
				1, &c));
			if (error) {
#ifdef SSIF_ERROR_DEBUG
				device_printf(dev, "SSIF: WRITE_CONT error %d\n",
				    error);
#endif
				goto fail;
			}
		}
	}

	/* Release the bus. */
	smbus_release_bus(smbus, dev);

	/* Give the BMC 100ms to chew on the request. */
	pause("ssifwt", hz / 10);

	/* Try to read the first packet. */
read_start:
	if (smbus_request_bus(smbus, dev, SMB_WAIT) != 0)
		return (0);
	count = SMBUS_DATA_SIZE;
	error = smbus_error(smbus_bread(smbus,
	    sc->ipmi_ssif_smbus_address, SMBUS_READ_START, &count, ssif_buf));
	if (error == ENXIO || error == EBUSY) {
		smbus_release_bus(smbus, dev);
#ifdef SSIF_DEBUG
		device_printf(dev, "SSIF: READ_START retry\n");
#endif
		/* Give the BMC another 10ms. */
		pause("ssifwt", hz / 100);
		goto read_start;
	}
	if (error) {
#ifdef SSIF_ERROR_DEBUG
		device_printf(dev, "SSIF: READ_START failed: %d\n", error);
#endif
		goto fail;
	}
#ifdef SSIF_DEBUG
	device_printf("SSIF: READ_START: ok\n");
#endif

	/*
	 * If this is the first part of a multi-part read, then we need to
	 * skip the first two bytes.
	 */
	if (count == SMBUS_DATA_SIZE && ssif_buf[0] == 0 && ssif_buf[1] == 1)
		offset = 2;
	else
		offset = 0;

	/* We had better get the reply header. */
	if (count < 3) {
		device_printf(dev, "SSIF: Short reply packet\n");
		goto fail;
	}

	/* Verify the NetFn/LUN. */
	if (ssif_buf[offset] != IPMI_REPLY_ADDR(req->ir_addr)) {
		device_printf(dev, "SSIF: Reply address mismatch\n");
		goto fail;
	}

	/* Verify the command. */
	if (ssif_buf[offset + 1] != req->ir_command) {
		device_printf(dev, "SMIC: Command mismatch\n");
		goto fail;
	}

	/* Read the completion code. */
	req->ir_compcode = ssif_buf[offset + 2];

	/* If this is a single read, just copy the data and return. */
	if (offset == 0) {
#ifdef SSIF_DEBUG
		dump_buffer(dev, "READ_SINGLE", ssif_buf, count);
#endif
		len = count - 3;
		bcopy(&ssif_buf[3], req->ir_reply,
		    min(req->ir_replybuflen, len));
		goto done;
	}

	/*
	 * This is the first part of a multi-read transaction, so copy
	 * out the payload and start looping.
	 */
#ifdef SSIF_DEBUG
	dump_buffer(dev, "READ_START", ssif_buf + 2, count - 2);
#endif
	bcopy(&ssif_buf[5], req->ir_reply, min(req->ir_replybuflen, count - 5));
	len = count - 5;
	block = 1;

	for (;;) {
		/* Read another packet via READ_CONT. */
		count = SMBUS_DATA_SIZE;
		error = smbus_error(smbus_bread(smbus,
		    sc->ipmi_ssif_smbus_address, SMBUS_READ_CONT, &count,
		    ssif_buf));
		if (error) {
#ifdef SSIF_ERROR_DEBUG
			printf("SSIF: READ_CONT failed: %d\n", error);
#endif
			goto fail;
		}
#ifdef SSIF_DEBUG
		device_printf(dev, "SSIF: READ_CONT... ok\n");
#endif

		/* Verify the block number.  0xff marks the last block. */
		if (ssif_buf[0] != 0xff && ssif_buf[0] != block) {
			device_printf(dev, "SSIF: Read wrong block %d %d\n",
			    ssif_buf[0], block);
			goto fail;
		}
		if (ssif_buf[0] != 0xff && count < SMBUS_DATA_SIZE) {
			device_printf(dev,
			    "SSIF: Read short middle block, length %d\n",
			    count);
			goto fail;
		}
#ifdef SSIF_DEBUG
		if (ssif_buf[0] == 0xff)
			dump_buffer(dev, "READ_END", ssif_buf + 1, count - 1);
		else
			dump_buffer(dev, "READ_CONT", ssif_buf + 1, count - 1);
#endif
		if (len < req->ir_replybuflen)
			bcopy(&ssif_buf[1], &req->ir_reply[len],
			    min(req->ir_replybuflen - len, count - 1));
		len += count - 1;

		/* If this was the last block we are done. */
		if (ssif_buf[0] != 0xff)
			break;
		block++;
	}

done:
	/* Save the total length and return success. */
	req->ir_replylen = len;
	smbus_release_bus(smbus, dev);
	return (1);

fail:
	smbus_release_bus(smbus, dev);
	return (0);
}
Exemplo n.º 15
0
int main(void)
{
	char serverID = 'S';
	char filename[256];
	unsigned char checksum[MD5_DIGEST_LENGTH];
	int filesize = 0;
	bool ack_completo = FALSE;
	bool mandar_ack = FALSE;

	/* Variable asociadas al paquete ENTRANTE */

	buffer_recv = (void *) malloc(BUFFER_SIZE);

	/* Puntero a la cabecera ethernet del paquete RECIBIDO */
	etherhead = buffer_recv;

	/* Puntero a la estructura que almacena la información de la cabecera ethernet del paquete RECIBIDO */
	eh = (struct ethhdr *) etherhead;

	int nonblock = 1;


	/* Variables para almacenar nuestra propia dirección ethernet */
	struct ifreq ifr;
	/* Indice de la interfaz Ethernet local */
	int ifindex = 0;


	/* Variables asociadas al paquete SALIENTE */

	buffer_sent = (void *) malloc(BUFFER_SIZE);
	etherhead_sent = buffer_sent;
	eh_sent = (struct ethhdr *) etherhead_sent;


	// REVISAR
	int length;					/* length of received packet */
	int sent;
	int dist;
	unsigned char *ack_posicion = NULL;
	int bytes_archivo = 0;
	char path[BUFFER_SIZE];
	unsigned char nro_secuencia = 0xEF, nro_secuencia_anterior = 0xEF;

	/* Variables asociadas a la ESCRITURA del archivo */

	void *buffer_write = NULL;
	buffer_write = (void *) malloc(BUFFER_SIZE*CANT_CHUNKS);	/*Buffer for Ethernet Frame */

	/* 
	 * Variable indica si el paquete recibido es el primero de la copia.
	 * Esta variable se vuelve a poner a 1 cuando ha llegado el final de
	 * un archivo y se espera el siguiente. En cualquier otro caso se pone
	 * a cero.
	 */
	unsigned int primer_paquete = 1;

	unsigned int posicion = 0;
//	unsigned int saldo = 0;
//	unsigned char anterior = 0xEF, nuevo = 0xEF;
	unsigned char nuevo = 0xEF;

	/* Variables asociada a las pruebas de retry */
	int i;
	fd_set rfds;
	struct timeval tv;
	int retval;
//	int cantidad_de_reintentos = 0;

	/* Buffer en 0xFF, para fines comparativos */
	void *null_buffer = NULL, *notnull_buffer = NULL;
	null_buffer = malloc(CANT_CHUNKS);
	notnull_buffer = malloc(CANT_CHUNKS);
    memset(null_buffer, 0x00, CANT_CHUNKS);
    memset(notnull_buffer, 0xFF, CANT_CHUNKS);


	/* COMIENZO DEL PROGRAMA */
	printf("Arrancando servidor\n");


	/* abre socket raw */
	s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if (s == -1)
		error("socket():");

	/* obtiene índice de la interfaz ethernet */
	strncpy(ifr.ifr_name, DEVICE, IFNAMSIZ);
	if (ioctl(s, SIOCGIFINDEX, &ifr) == -1)
		error("SIOCGIFINDEX");
	ifindex = ifr.ifr_ifindex;

	/* obtiene la MAC address de la interfaz */
	if (ioctl(s, SIOCGIFHWADDR, &ifr) == -1)
		error("SIOCGIFINDEX");

	/* almacena la información de nuestra propia MAC address en los bytes correspondientes */
	for (i = 0; i < 6; i++) {
		src_mac[i] = ifr.ifr_hwaddr.sa_data[i];
	}

	printf
		("MAC address local: %02X:%02X:%02X:%02X:%02X:%02X\n",
		 src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4],
		 src_mac[5]);


	/* Crea la estructura de dirección para el Socket Raw */
	socket_address.sll_family = PF_PACKET;
	socket_address.sll_protocol = htons(ETH_P_IP);
	socket_address.sll_ifindex = ifindex;
	socket_address.sll_hatype = ARPHRD_ETHER;
	socket_address.sll_pkttype = PACKET_OTHERHOST;
	socket_address.sll_halen = ETH_ALEN;
	socket_address.sll_addr[6] = 0x00;
	socket_address.sll_addr[7] = 0x00;

	memcpy((void *) (buffer_sent + ETH_HEADER_LEN + 1), (const void *) &serverID, 1);
	memcpy((void *) (etherhead_sent + ETH_MAC_LEN), (const void *) src_mac, ETH_MAC_LEN);

	/*prepare sockaddr_ll */
	socket_address.sll_addr[0] = eh_sent->h_dest[0];
	socket_address.sll_addr[1] = eh_sent->h_dest[1];
	socket_address.sll_addr[2] = eh_sent->h_dest[2];
	socket_address.sll_addr[3] = eh_sent->h_dest[3];
	socket_address.sll_addr[4] = eh_sent->h_dest[4];
	socket_address.sll_addr[5] = eh_sent->h_dest[5];

	/* Defino función para salida por interrupción del programa */
	signal(SIGINT, sigint);

	printf ("Esperando paquetes entrantes\n");


	/* startOfRx */
//	startOfRx();

	/* Configuro el socket como non-block */
	if (ioctl(s, FIONBIO, (char *)&nonblock) < 0)
		error("ioctl()");

	long int total_escrito = 0;

	while (1) {
		/* Espero paquete entrante */
		FD_ZERO(&rfds);
		FD_SET(s, &rfds);

		/* Establece timeout */
		tv.tv_sec = 0;
		tv.tv_usec = TIMEOUT;

		retval = select(s+1, &rfds, NULL, NULL, &tv);

		if (retval == -1)
			error("select()");
		else if (retval) {
			//printf("Se detectó paquete entrante antes del timeout\n");
			/* Recupero dato leído */
			length = recvfrom(s, buffer_recv, BUFFER_SIZE, 0, NULL, NULL);
			if (length == -1)
				error("recvfrom():");

			/*
			 * Compruebo si el dato recibido se corresponde a un socket raw
			 * 1) Ethertype == 0x0
			 * 2) Direccion ethernet de destino == nuestra MAC
			 * 3) Primer byte de datos == nro. de secuencia
			 */
			if (eh->h_proto == ETH_P_NULL
				&& memcmp((const void *) eh->h_dest, (const void *) src_mac,
						  ETH_MAC_LEN) == 0) {

#ifdef DEBUG
				printf("Se detectó paquete socket raw\n");
#endif

				data = buffer_recv + ETH_HEADER_LEN;
				nro_secuencia = (unsigned char) *data;

				/*
				 * Copio nro de secuencia para ACK.
				 * Si recibí el nro. de secuencia que esperaba, mando el ACK
				 * con ese número.
				 * Si recibo otra cosa, puedo suponer que se perdió un paquete
				 * asi que pido nuevamente el anterior.
				 */
				nuevo = (unsigned int) nro_secuencia;

				/* Nombre del archivo */
				if (nuevo == 0xFF) {
					/* Blanquea buffer donde almacena lo que escribe en archivo */
					memset(buffer_write, 0x0, BUFFER_SIZE*CANT_CHUNKS);

					memcpy((void *) buffer_write, (void *) (buffer_recv + ETH_HEADER_LEN + RAW_HEADER_LEN), length - ETH_HEADER_LEN - RAW_HEADER_LEN);
					sscanf(buffer_write, "%s %d", filename, &filesize);

					sprintf(path, "%s/%s", PATH_DESTINO, (char *) filename);
					printf("Recibiendo archivo %s de tamaño %d\n", path, filesize);

					/* Archivo está abierto actualmente. Lo cierro. */
					if (filefd != 0) {
						close(filefd);
						filefd = 0;
					}

					/* Abro archivo si no ha sido abierto */
//					if (filefd == 0) {
						if ((filefd = (open(path, O_WRONLY | O_CREAT | O_TRUNC))) < 0) {
							error("Error al intentar leer archivo local.\n");
						}
//					}

					/* Blanquea buffer de paquete saliente */
					memset((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN), 0x0, ETH_MIN_LEN - ETH_HEADER_LEN - RAW_HEADER_LEN);

					/* Blanquea buffer donde almacena lo que escribe en archivo */
//					memset(buffer_write, 0x0, BUFFER_SIZE*CANT_CHUNKS);

					/* Blanqueo contador de bytes a escribir en archivo */
					bytes_archivo = 0;

					//nro_secuencia_ant = 0xEF;
					nro_secuencia_anterior = 0x00;

					sent = enviar_ack(etherhead, nro_secuencia);
					if (sent == -1)
						error("enviar_ack():");

//					anterior = 0xEF;
					total_escrito = 0;
				/* EOF */
				} else if (nuevo == 0xFE) {
					/*
					 * Si el buffer de ACK no está en blanco, entonces
					 * hay un saldo en el buffer que debo escribir en
					 * el archivo.
					 */
//					printf("HAY ALGO PARA ESCRIBIR?: saldo %u", saldo);
//					dump_buffer(buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN, CANT_CHUNKS);
					if (memcmp((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN), (void *) null_buffer, CANT_CHUNKS) != 0) {
//						write(filefd, buffer_write, saldo);
						write(filefd, buffer_write, bytes_archivo);
//						total_escrito += saldo;
						total_escrito += bytes_archivo;
						printf("\r%lu\n", total_escrito);
					}

					if (filefd != 0) {
						close (filefd);
						printf("Archivo %s fue recibido completamente\n", path);
					}

					memset((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN), 0x0, CANT_CHUNKS);

					/* El siguiente igualamiento es por si debe retransmitir paquete de finalización */
					nro_secuencia_anterior = nro_secuencia;
					sent = enviar_ack(etherhead, nro_secuencia_anterior);
					if (sent == -1)
						error("enviar_ack():");

//					primer_paquete = 0;
					filefd = 0;







				/* CHECKSUM */
				} else if (nuevo == 0xFD) {
					printf("Calculando MD5sum\n");
					md5sum(path, &checksum[0]);
/*
	    int n=0;
        for(n=0; n<MD5_DIGEST_LENGTH; n++)
                printf("%02x ", checksum[n]);
        printf("\n");



					printf("MD5sum: %s\n", checksum);
*/
					memcpy((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN), (void *) checksum, MD5_DIGEST_LENGTH);
					/* El siguiente igualamiento es por si debe retransmitir paquete con CHECKSUM */
					nro_secuencia_anterior = nro_secuencia;
					sent = enviar_ack(etherhead, nro_secuencia_anterior);
					if (sent == -1)
						error("enviar_ack():");

					primer_paquete = 0;
					memset(buffer_write, 0x0, BUFFER_SIZE*CANT_CHUNKS);



				/* Contenido del archivo */
				} else {
					/* 
					 * El chunk recibido es de la porción esperada o no ?
					 */
					dist = distancia(nro_secuencia, nro_secuencia_anterior);
					if (dist >= CANT_CHUNKS) {
						/* 
						 * En el paso anterior se envio ACK ?
						 */
						printf("\n\nACK ESTA COMPLETO AL COMIENZO DE ESTE CICLO ?: %c\n", (ack_completo) ? 'S' : 'N');
						if (ack_completo) {
							/* Escribo en el archivo */
							write(filefd, buffer_write, bytes_archivo);
							total_escrito += CHUNK * CANT_CHUNKS;
							printf("Total Escrito: %lu", total_escrito);

							/* Blanqueo buffer para archivo. Se puede evitar */
							/* Blanqueo contador de bytes a escribir en archivo */
							bytes_archivo = 0;

							/* Blanqueo ACK */
						printf("\n\nBLANQUEO ACK AL COMIENZO DE ESTE CICLO\n");
							memset((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN), 0x0, CANT_CHUNKS);
							ack_completo = 0;

							/* Almaceno la siguiente porcion a esperar */
							nro_secuencia_anterior += CANT_CHUNKS;
							if (nro_secuencia_anterior >= (0xF0 - CANT_CHUNKS)) {
								nro_secuencia_anterior -= (0xF0 - CANT_CHUNKS);
							}

						/* 
						 * Si en el paso anterior no se envio ACK, hay un ERROR
						 */
						} else {
							printf("ERROR. Nro secuencia %u, Nro secuencia anterior %u, distancia %u\n", nro_secuencia, nro_secuencia_anterior, dist);
							exit(0);
						}
					}


					/* 
					 * La posicion en el ACK correspondiente a este chunk NO está seteada aún ?
					 */
					posicion = nro_secuencia % CANT_CHUNKS;
//					printf("COMPLETA POSICION %d para nro de secuencia %d\n", posicion * CHUNK, nro_secuencia);
//					printf("VALOR DE LA DIRECCION DEL BUFFER %p\n", buffer_sent);
					ack_posicion = (unsigned char *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN + posicion);
					printf("VALOR DE LA POSICION %d EN EL ACK %d\n", posicion, *ack_posicion);
					if ((*ack_posicion) == 0) {

						/* Seteo posicion correspondiente en ACK */
						memset((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN + posicion), 0xFF, 1);
//						*ack_posicion = 0xFF;
//printf("LUEGO ...\n");
//dump_buffer(buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN, CANT_CHUNKS);
					
						/* Completo buffer para posterior escritura en archivo */
						memcpy((void *) (buffer_write + posicion * CHUNK), (void *) (buffer_recv + ETH_HEADER_LEN + RAW_HEADER_LEN), length - ETH_HEADER_LEN - RAW_HEADER_LEN);

						bytes_archivo += length - ETH_HEADER_LEN - RAW_HEADER_LEN;
					} else {
printf("Esa posicion ya está escrita. Salteando\n");
					}

					/* 
					 * La grilla de ACK está completamente seteada ?
					 */
					if (memcmp((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN), (void *) notnull_buffer, CANT_CHUNKS) == 0) {
						/* Seteo flag que indica que el ACK está completo */
						ack_completo = TRUE;

						/* Seteo flag que indica que se debe enviar ACK */
						mandar_ack = 1;
					} else {
						/* 
						 * El nro. de secuencia es el último de la porción ?
						 */
//						printf("PRIMER PAQUETE: %d\n", primer_paquete);
						if ((((nro_secuencia + 1) % CANT_CHUNKS) == 0) && (! primer_paquete)) {
							printf("El nro de secuencia %d es el último de la porción. Debo mandar ACK.\n", nro_secuencia);
							mandar_ack = 1;
						} else {
							/* 
							 * Es la última porción del archivo ?
							 */
							printf("Total escrito: %lu Filesize: %d\n", total_escrito, filesize);
							if ((total_escrito + (posicion + 1) * CHUNK) >= filesize) {
								printf("ULTIMA PORCION DEL ARCHIVO\n");
								mandar_ack = 1;
							} else
								mandar_ack = 0;
						}
					}

					dump_buffer(buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN, CANT_CHUNKS);

					if (mandar_ack) {
						/* Mando ACK al cliente */
						printf("MANDO ACK para nro de secuencia %d\n", nro_secuencia_anterior);
						dump_buffer(buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN, CANT_CHUNKS);

						sent = enviar_ack(etherhead, nro_secuencia_anterior);
						if (sent == -1)
							error("enviar_ack():");

						/* Escribo en archivo */
//						write(filefd, buffer_write, CHUNK * CANT_CHUNKS);




						//// NO SE DEBE ESCRIBIR SIEMPRE EL ARCHIVO. A VECES SE MANDA
						//// EL MISMO ACK DE ANTES
/*
						write(filefd, buffer_write, bytes_archivo);
						total_escrito += CHUNK * CANT_CHUNKS;
						printf("Total Escrito: %lu", total_escrito);
*/
					}








					printf("\n\nACK ESTA COMPLETO AL FINAL DE ESTE CICLO ?: %c\n", (ack_completo) ? 'S' : 'N');




#if 0
					/* Si envía secuencia de la siguiente ráfaga, confirma que llegó el ACK al cliente */
						if (ack_completo) {
						
							////

							saldo = 0;
						}
					}



					/*
					 * Mientras el ACK no esté completo, escribo en el buffer que luego
					 * irá a parar al archivo.
					 */
					if (ack_completo == 0) {

						////

						saldo += length - ETH_HEADER_LEN - RAW_HEADER_LEN;
						dump_buffer(buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN, CANT_CHUNKS);
					}


					printf("TOTAL: %lu, POS: %d, CHUNK: %d\n", total_escrito, posicion, CHUNK);

						////
						ack_completo = 1;


					/*
					 * La grilla en buffer de respuesta está en uno, o
					 * se leyeron menos bytes que el tamaño del CHUNK
					 * (o sea, último paquete).
					 * Mando ACK
					 */
/*
					if ((memcmp((void *) (buffer_sent + ETH_HEADER_LEN + RAW_HEADER_LEN), (void *) notnull_buffer, CANT_CHUNKS) == 0) || (length < CHUNK)) {
						sent = enviar_ack(etherhead, nro_secuencia_anterior);
						if (sent == -1)
							error("enviar_ack():");
					}
*/
/*
					if ((nuevo == (anterior + 1)) || (nuevo == 0 && anterior == 0xEF)) 
						memcpy((void *) buffer_write, (void *) (buffer_recv + ETH_HEADER_LEN + RAW_HEADER_LEN), length - ETH_HEADER_LEN - RAW_HEADER_LEN);
						write(filefd, buffer_write, length - ETH_HEADER_LEN - RAW_HEADER_LEN);

						nro_secuencia_ant = nro_secuencia;
						anterior = nuevo;

					}
*/

//					dump_buffer(buffer_recv, length);

#endif


					primer_paquete = 0;
//					printf("SALDO: %u\n", saldo);







				}
/*
				sent = enviar_ack(etherhead, nro_secuencia);
				if (sent == -1)
					error("enviar_ack():");
*/

				answered_packets++;
			} /* if (eh->h_proto == ETH_P_NULL && memcmp((const void *) eh->h_dest, (const void *) src_mac, ETH_MAC_LEN) == 0) { */

			total_packets++;


		/* Timeout en la espera por un paquete entrante */
		} else {
Exemplo n.º 16
0
int
dbg_free(void *buffer, char *file, char *function, int line)
{
	int i = 0;
	void *buf;

	/* If nullpointer remember */
	if (buffer == NULL) {
		i = number_alloc_list++;

		assert(number_alloc_list < MAX_ALLOC_LIST);

		alloc_list[i].ptr = buffer;
		alloc_list[i].size = 0;
		alloc_list[i].file = file;
		alloc_list[i].func = function;
		alloc_list[i].line = line;
		alloc_list[i].type = 2;
		if (debug & 1)
			printf("free NULL in %s, %3d, %s\n", file,
			       line, function);

		debug |= 512;	/* Memory Error detect */

		return n;
	} else
		buf = buffer;

	while (i < number_alloc_list) {
		if (alloc_list[i].type == 9 && alloc_list[i].ptr == buf) {
			if (*
			    ((long *) ((char *) alloc_list[i].ptr +
				       alloc_list[i].size)) ==
			    alloc_list[i].csum)
				alloc_list[i].type = 0;	/* Release */
			else {
				alloc_list[i].type = 1;	/* Overrun */
				if (debug & 1) {
					printf("free corrupt, buffer overrun [%3d:%3d], %p, %4ld at %s, %3d, %s\n",
					       i, number_alloc_list,
					       buf, alloc_list[i].size, file,
					       line, function);
					dump_buffer(alloc_list[i].ptr,
						    alloc_list[i].size + sizeof (long));
					printf("Check_sum\n");
					dump_buffer((char *) &alloc_list[i].csum,
						    sizeof(long));

					debug |= 512;	/* Memory Error detect */
				}
			}
			break;
		}
		i++;
	}

	/*  Not found */
	if (i == number_alloc_list) {
		printf("Free ERROR %p\n", buffer);
		number_alloc_list++;

		assert(number_alloc_list < MAX_ALLOC_LIST);

		alloc_list[i].ptr = buf;
		alloc_list[i].size = 0;
		alloc_list[i].file = file;
		alloc_list[i].func = function;
		alloc_list[i].line = line;
		alloc_list[i].type = 4;
		debug |= 512;

		return n;
	}

	if (buffer != NULL)
		xfree(buffer);

	if (debug & 1)
		printf("free  [%3d:%3d], %p, %4ld at %s, %3d, %s\n",
		       i, number_alloc_list, buf,
		       alloc_list[i].size, file, line, function);

	free_list[f].file = file;
	free_list[f].line = line;
	free_list[f].func = function;
	free_list[f].ptr = buffer;
	free_list[f].type = 8;
	free_list[f].csum = i;	/* Using this field for row id */

	f++;
	f &= 255;
	n--;

	return n;
}
Exemplo n.º 17
0
static duk_ret_t test_1(duk_context *ctx, void *udata) {
	duk_size_t i, n;
	char *buf;

	(void) udata;

	duk_set_top(ctx, 0);

	duk_push_undefined(ctx);
	duk_push_null(ctx);
	duk_push_true(ctx);
	duk_push_false(ctx);
	duk_push_nan(ctx);
	duk_push_number(ctx, -INFINITY);
	duk_push_number(ctx, +INFINITY);
	duk_push_number(ctx, -0.0);
	duk_push_number(ctx, +0.0);
	duk_push_int(ctx, 123);

	duk_push_string(ctx, "foo");
	duk_push_lstring(ctx, "foo\0bar", 7);  /* internal NULs are kept */
	duk_push_object(ctx);
	buf = (char *) duk_push_fixed_buffer(ctx, 0);
	buf = (char *) duk_push_fixed_buffer(ctx, 16);
	for (i = 0; i < 16; i++) {
		buf[i] = i;
	}
	buf = (char *) duk_push_dynamic_buffer(ctx, 0);
	buf = (char *) duk_push_dynamic_buffer(ctx, 16);
	for (i = 0; i < 16; i++) {
		buf[i] = i;
	}
	duk_push_pointer(ctx, (void *) NULL);
	duk_push_pointer(ctx, (void *) 0xdeadbeef);

	n = duk_get_top(ctx);
	printf("top: %ld\n", (long) n);
	for (i = 0; i < n; i++) {
		duk_int_t t1, t2;
		void *ptr;
		duk_size_t sz;

		duk_dup(ctx, i);
		t1 = duk_get_type(ctx, -1);
		sz = (duk_size_t) 0xdeadbeef;
		ptr = duk_to_buffer(ctx, -1, &sz);
		t2 = duk_get_type(ctx, -1);
		printf("index %ld, type %ld -> %ld, ptr-is-NULL %d, size %lu\n",
		       (long) i, (long) t1, (long) t2,
		       (sz == 0 ? -1 : (ptr == NULL ? 1 : 0)),
		       (unsigned long) sz);
		dump_buffer(ctx);
		duk_pop(ctx);

		/* just check that this doesn't break */
		duk_dup(ctx, i);
		ptr = duk_to_buffer(ctx, -1, NULL);
		duk_pop(ctx);
	}

	return 0;
}
Exemplo n.º 18
0
static int readv_f(int argc, char **argv)
{
    struct timeval t1, t2;
    int Cflag = 0, qflag = 0, vflag = 0;
    int c, cnt;
    char *buf;
    int64_t offset;
    /* Some compilers get confused and warn if this is not initialized.  */
    int total = 0;
    int nr_iov;
    QEMUIOVector qiov;
    int pattern = 0;
    int Pflag = 0;

    while ((c = getopt(argc, argv, "CP:qv")) != EOF) {
        switch (c) {
        case 'C':
            Cflag = 1;
            break;
        case 'P':
            Pflag = 1;
            pattern = parse_pattern(optarg);
            if (pattern < 0) {
                return 0;
            }
            break;
        case 'q':
            qflag = 1;
            break;
        case 'v':
            vflag = 1;
            break;
        default:
            return command_usage(&readv_cmd);
        }
    }

    if (optind > argc - 2) {
        return command_usage(&readv_cmd);
    }


    offset = cvtnum(argv[optind]);
    if (offset < 0) {
        printf("non-numeric length argument -- %s\n", argv[optind]);
        return 0;
    }
    optind++;

    if (offset & 0x1ff) {
        printf("offset %" PRId64 " is not sector aligned\n",
               offset);
        return 0;
    }

    nr_iov = argc - optind;
    buf = create_iovec(&qiov, &argv[optind], nr_iov, 0xab);
    if (buf == NULL) {
        return 0;
    }

    gettimeofday(&t1, NULL);
    cnt = do_aio_readv(&qiov, offset, &total);
    gettimeofday(&t2, NULL);

    if (cnt < 0) {
        printf("readv failed: %s\n", strerror(-cnt));
        goto out;
    }

    if (Pflag) {
        void *cmp_buf = g_malloc(qiov.size);
        memset(cmp_buf, pattern, qiov.size);
        if (memcmp(buf, cmp_buf, qiov.size)) {
            printf("Pattern verification failed at offset %"
                   PRId64 ", %zd bytes\n", offset, qiov.size);
        }
        g_free(cmp_buf);
    }

    if (qflag) {
        goto out;
    }

    if (vflag) {
        dump_buffer(buf, offset, qiov.size);
    }

    /* Finally, report back -- -C gives a parsable format */
    t2 = tsub(t2, t1);
    print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);

out:
    qemu_io_free(buf);
    return 0;
}
Exemplo n.º 19
0
static int sda_test_raw(void)
{
	const struct emv_pk *pk = &vsdc_01;

	struct crypto_pk *kcp = crypto_pk_open(PK_RSA,
			pk->modulus, pk->mlen,
			pk->exp, pk->elen);
	if (!kcp)
		return 1;

	unsigned char *ipk_data;
	size_t ipk_data_len;
	ipk_data = crypto_pk_encrypt(kcp, issuer_cert, sizeof(issuer_cert), &ipk_data_len);
	crypto_pk_close(kcp);

	if (!ipk_data)
		return 1;

	dump_buffer(ipk_data, ipk_data_len, stdout);

	size_t ipk_pk_len = ipk_data[13];
	unsigned char *ipk_pk = malloc(ipk_pk_len);
	memcpy(ipk_pk, ipk_data + 15, ipk_data_len - 36);
	memcpy(ipk_pk + ipk_data_len - 36, issuer_rem, sizeof(issuer_rem));

	struct crypto_hash *ch;
	ch = crypto_hash_open(HASH_SHA_1);
	if (!ch) {
		free(ipk_pk);
		free(ipk_data);
		return 1;
	}

	crypto_hash_write(ch, ipk_data + 1, 14);
	crypto_hash_write(ch, ipk_pk, ipk_pk_len);
	crypto_hash_write(ch, issuer_exp, sizeof(issuer_exp));

	unsigned char *h = crypto_hash_read(ch);
	if (!h) {
		crypto_hash_close(ch);
		free(ipk_pk);
		free(ipk_data);
		return 1;
	}

	dump_buffer(h, 20, stdout);

	if (memcmp(ipk_data + ipk_data_len - 21, h, 20)) {
		crypto_hash_close(ch);
		free(ipk_pk);
		free(ipk_data);
		return 1;
	}

	crypto_hash_close(ch);
	free(ipk_data);

	struct crypto_pk *ikcp = crypto_pk_open(PK_RSA, ipk_pk, (int) ipk_pk_len,
			issuer_exp, (int) sizeof(issuer_exp));
	free(ipk_pk);
	if (!ikcp)
		return 1;

	size_t ssad_len;
	unsigned char *ssad = crypto_pk_encrypt(ikcp, ssad_cr, sizeof(ssad_cr), &ssad_len);
	crypto_pk_close(ikcp);
	if (!ssad)
		return 1;

	dump_buffer(ssad, ssad_len, stdout);

	ch = crypto_hash_open(HASH_SHA_1);
	if (!ch) {
		free(ssad);
		return 1;
	}

	crypto_hash_write(ch, ssad + 1, ssad_len - 22);
	crypto_hash_write(ch, ssd1, sizeof(ssd1));

	unsigned char *h2 = crypto_hash_read(ch);
	if (!h2) {
		crypto_hash_close(ch);
		free(ssad);
		return 1;
	}

	dump_buffer(h2, 20, stdout);

	crypto_hash_close(ch);

	free(ssad);

	return 0;
}
Exemplo n.º 20
0
int test(mrp_fragbuf_t *buf, size_t *chunks, int dump_interval)
{
    char *messages[] = {
        "Ticking away the moments",
        "That make up a dull day",
        "Fritter and waste the hours",
        "In an off-hand way",
        "Kicking around on a piece of ground",
        "In your home town",
        "Waiting for someone or something",
        "To show you the way",
        "Tired of lying in the sunshine",
        "Staying home to watch the rain",
        "You are young and life is long",
        "And there is time to kill today",
        "And then the one day you find",
        "Ten years have got behind you",
        "No one told you when to run",
        "You missed the starting gun",
        "And you run and you run",
        "To catch up with the sun",
        "But it's sinking",
        "Racing around",
        "To come up behind you again",
        "The sun is the same",
        "In a relative way",
        "But you're older",
        "Shorter of breath",
        "And one day closer to death",
        "Every year is getting shorter",
        "Never seem to find the time",
        "Plans that either come to naught",
        "Or half a page of scribbled lines",
        "Hanging on in quiet desperation",
        "Is the English way",
        "The time is gone",
        "The song is over",
        "Thought I'd something more to say",
        "Home",
        "Home again",
        "I like to be here",
        "When I can",
        "When I come home",
        "Cold and tired",
        "It's good to warm my bones",
        "Beside the fire",
        "Far away",
        "Across the field",
        "Tolling on the iron bell",
        "Calls the faithful to their knees",
        "To hear the softly spoken magic spell...",
        "test #1",
        "test #2",
        "this is a test #3",
        "message #4",
        "message #5",
        "test message #6",
        "a test #7",
        "the quick brown (#8)",
        "fox (#9)",
        "jumps over the (#10)",
        "lazy dog (#11)",
        "this is another test message (#12)",
        "and here is one more for you (#13)",
        "foo (#14)",
        "bar (#15)",
        "foobar (#16)",
        "barfoo (#17)",
        "xyzzykukkuluuruu (#18)"
    };

    char          *msg, *p;
    uint32_t       size, nbo_size;
    size_t         n, total;
    int            dump, chk, offs, i, j;

    dump = chk = offs = 0;

    for (i = 0; i < (int)MRP_ARRAY_SIZE(messages); i++) {
        msg   = messages[i];
        size  = strlen(msg);

        total = 0;
        p     = msg;

        if (ctx.framed) {
            nbo_size = htobe32(size);
            if (!mrp_fragbuf_push(buf, &nbo_size, sizeof(nbo_size)))
                fatal("failed to push message size to buffer");
        }

        for (j = 0; *p != '\0'; j++) {
            if (!chunks[j])
                j = 0;
            n = chunks[j];
            if (n > strlen(p))
                n = strlen(p);

            mrp_debug("pushing %zd bytes (%*.*s)...", n, (int)n, (int)n, p);

            if (!mrp_fragbuf_push(buf, p, n))
                fatal("failed to push %*.*s to buffer", (int)n, (int)n, p);

            p     += n;
            total += n;

            dump++;

            if (!dump_interval ||
                (dump_interval > 0 && !(dump % dump_interval)))
                dump_buffer(buf, messages, &chk, &offs);
        }

        if (dump_interval < -1) {
            if (i && !(i % -dump_interval))
                dump_buffer(buf, messages, &chk, &offs);
        }
    }

    dump_buffer(buf, messages, &chk, &offs);

    return TRUE;
}
Exemplo n.º 21
0
/**
 * @brief   ipi_shmem_echo() - shared memory IPI demo
 *          This task will:
 *          * Get the timestamp and put it into the ping shared memory
 *          * Update the shared memory descriptor for the new available
 *            ping buffer.
 *          * Trigger IPI to notifty the remote.
 *          * Repeat the above steps until it sends out all the packages.
 *          * Monitor IPI interrupt, verify every received package.
 *          * After all the packages are received, it sends out shutdown
 *            message to the remote.
 *
 * @param[in] ipi_io - IPI metal i/o region
 * @param[in] shm_io - shared memory metal i/o region
 * @return - return 0 on success, otherwise return error number indicating
 *           type of error.
 */
static int ipi_shmem_echo(struct metal_io_region *ipi_io,
		struct metal_io_region *shm_io)
{
	int ret;
	uint32_t i;
	uint32_t rx_avail;
	unsigned long tx_avail_offset, rx_avail_offset;
	unsigned long rx_used_offset;
	unsigned long tx_addr_offset, rx_addr_offset;
	unsigned long tx_data_offset, rx_data_offset;
	unsigned long long tstart, tend;
	long long tdiff;
	long long tdiff_avg_s = 0, tdiff_avg_ns = 0;
	void *txbuf = NULL, *rxbuf = NULL, *tmpptr;
	struct msg_hdr_s *msg_hdr;
	uint32_t ipi_mask = IPI_MASK;
	uint32_t tx_phy_addr_32;

	txbuf = metal_allocate_memory(BUF_SIZE_MAX);
	if (!txbuf) {
		LPERROR("Failed to allocate local tx buffer for msg.\n");
		ret = -ENOMEM;
		goto out;
	}
	rxbuf = metal_allocate_memory(BUF_SIZE_MAX);
	if (!rxbuf) {
		LPERROR("Failed to allocate local rx buffer for msg.\n");
		ret = -ENOMEM;
		goto out;
	}

	/* Clear shared memory */
	metal_io_block_set(shm_io, 0, 0, metal_io_region_size(shm_io));

	/* Set tx/rx buffer address offset */
	tx_avail_offset = SHM_DESC_OFFSET_TX + SHM_DESC_AVAIL_OFFSET;
	rx_avail_offset = SHM_DESC_OFFSET_RX + SHM_DESC_AVAIL_OFFSET;
	rx_used_offset = SHM_DESC_OFFSET_RX + SHM_DESC_USED_OFFSET;
	tx_addr_offset = SHM_DESC_OFFSET_TX + SHM_DESC_ADDR_ARRAY_OFFSET;
	rx_addr_offset = SHM_DESC_OFFSET_RX + SHM_DESC_ADDR_ARRAY_OFFSET;
	tx_data_offset = SHM_DESC_OFFSET_TX + SHM_BUFF_OFFSET_TX;
	rx_data_offset = SHM_DESC_OFFSET_RX + SHM_BUFF_OFFSET_RX;

	LPRINTF("Start echo flood testing....\n");
	LPRINTF("Sending msgs to the remote.\n");

	for (i = 0; i < PKGS_TOTAL; i++) {

		/* Construct a message to send */
		tmpptr = txbuf;
		msg_hdr = tmpptr;
		msg_hdr->index = i;
		msg_hdr->len = sizeof(tstart);
		tmpptr += sizeof(struct msg_hdr_s);
		tstart = get_timestamp();
		*(unsigned long long *)tmpptr = tstart;

		/* copy message to shared buffer */
		metal_io_block_write(shm_io, tx_data_offset, msg_hdr,
			sizeof(struct msg_hdr_s) + msg_hdr->len);

		/* Write to the address array to tell the other end
		 * the buffer address.
		 */
		tx_phy_addr_32 = (uint32_t)metal_io_phys(shm_io,
					tx_data_offset);
		metal_io_write32(shm_io, tx_addr_offset, tx_phy_addr_32);
		tx_data_offset += sizeof(struct msg_hdr_s) + msg_hdr->len;
		tx_addr_offset += sizeof(uint32_t);

		/* Increase number of available buffers */
		metal_io_write32(shm_io, tx_avail_offset, (i + 1));
		/* Kick IPI to notify data has been put to shared buffer */
		metal_io_write32(ipi_io, IPI_TRIG_OFFSET, ipi_mask);
	}

	LPRINTF("Waiting for messages to echo back and verify.\n");
	i = 0;
	tx_data_offset = SHM_DESC_OFFSET_TX + SHM_BUFF_OFFSET_TX;
	while (i != PKGS_TOTAL) {
		wait_for_notified(&remote_nkicked);
		rx_avail = metal_io_read32(shm_io, rx_avail_offset);
		while (i != rx_avail) {
			uint32_t rx_phy_addr_32;

			/* Received pong from the other side */

			/* Get the buffer location from the shared memory
			 * rx address array.
			 */
			rx_phy_addr_32 = metal_io_read32(shm_io,
					rx_addr_offset);
			rx_data_offset = metal_io_phys_to_offset(shm_io,
					(metal_phys_addr_t)rx_phy_addr_32);
			if (rx_data_offset == METAL_BAD_OFFSET) {
				LPERROR("failed to get rx [%d] offset: 0x%x.\n",
					i, rx_phy_addr_32);
				ret = -EINVAL;
				goto out;
			}
			rx_addr_offset += sizeof(rx_phy_addr_32);

			/* Read message header from shared memory */
			metal_io_block_read(shm_io, rx_data_offset, rxbuf,
				sizeof(struct msg_hdr_s));
			msg_hdr = (struct msg_hdr_s *)rxbuf;

			/* Check if the message header is valid */
			if (msg_hdr->index != (uint32_t)i) {
				LPERROR("wrong msg: expected: %d, actual: %d\n",
					i, msg_hdr->index);
				ret = -EINVAL;
				goto out;
			}
			if (msg_hdr->len != sizeof(tstart)) {
				LPERROR("wrong msg: length invalid: %lu, %u.\n",
					sizeof(tstart), msg_hdr->len);
				ret = -EINVAL;
				goto out;
			}
			/* Read message */
			rx_data_offset += sizeof(*msg_hdr);
			metal_io_block_read(shm_io,
					rx_data_offset,
					rxbuf + sizeof(*msg_hdr), msg_hdr->len);
			rx_data_offset += msg_hdr->len;
			/* increase rx used count to indicate it has consumed
			 * the received data */
			metal_io_write32(shm_io, rx_used_offset, (i + 1));

			/* Verify message */
			/* Get tx message previously sent*/
			metal_io_block_read(shm_io, tx_data_offset, txbuf,
					sizeof(*msg_hdr) + sizeof(tstart));
			tx_data_offset += sizeof(*msg_hdr) + sizeof(tstart);
			/* Compare the received message and the sent message */
			ret = memcmp(rxbuf, txbuf,
				sizeof(*msg_hdr) + sizeof(tstart));
			if (ret) {
				LPERROR("data[%u] verification failed.\n", i);
				LPRINTF("Expected:");
				dump_buffer(txbuf,
					sizeof(*msg_hdr) + sizeof(tstart));
				LPRINTF("Actual:");
				dump_buffer(rxbuf,
					sizeof(*msg_hdr) + sizeof(tstart));
				ret = -EINVAL;
				goto out;
			}

			i++;
		}
	}
	tend = get_timestamp();
	tdiff = tend - tstart;

	/* Send shutdown message */
	tmpptr = txbuf;
	msg_hdr = tmpptr;
	msg_hdr->index = i;
	msg_hdr->len = strlen(SHUTDOWN);
	tmpptr += sizeof(struct msg_hdr_s);
	sprintf(tmpptr, SHUTDOWN);
	/* copy message to shared buffer */
	metal_io_block_write(shm_io,
		tx_data_offset,
		msg_hdr,
		sizeof(struct msg_hdr_s) + msg_hdr->len);

	tx_phy_addr_32 = (uint32_t)metal_io_phys(shm_io,
					tx_data_offset);
	metal_io_write32(shm_io, tx_addr_offset, tx_phy_addr_32);
	metal_io_write32(shm_io, tx_avail_offset, PKGS_TOTAL + 1);
	LPRINTF("Kick remote to notify shutdown message sent...\n");
	metal_io_write32(ipi_io, IPI_TRIG_OFFSET, ipi_mask);

	tdiff /= PKGS_TOTAL;
	tdiff_avg_s = tdiff / NS_PER_S;
	tdiff_avg_ns = tdiff % NS_PER_S;
	LPRINTF("Total packages: %d, time_avg = %lds, %ldns\n",
		i, (long int)tdiff_avg_s, (long int)tdiff_avg_ns);

	ret = 0;
out:
	if (txbuf)
		metal_free_memory(txbuf);
	if (rxbuf)
		metal_free_memory(rxbuf);
	return ret;
}