view simtool/hexread.c @ 141:0b8a936f4542

fc-uicc-tool: need to select MF before DF_TELECOM
author Mychaela Falconia <falcon@freecalypso.org>
date Thu, 04 Feb 2021 05:04:12 +0000
parents 4aaf722ab933
children 54e33e9238b6
line wrap: on
line source

/*
 * This module contains the function for reading hex files,
 * to be used in the implementation of manual write commands.
 */

#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>

decode_hex_digit(c)
{
	if (c >= '0' && c <= '9')
		return(c - '0');
	if (c >= 'A' && c <= 'F')
		return(c - 'A' + 10);
	if (c >= 'a' && c <= 'f')
		return(c - 'a' + 10);
	return(-1);
}

read_hex_data_file(filename, databuf)
	char *filename;
	u_char *databuf;
{
	FILE *inf;
	unsigned count;
	int c, c2;

	inf = fopen(filename, "r");
	if (!inf) {
		perror(filename);
		return(-1);
	}
	for (count = 0; ; count++) {
		do
			c = getc(inf);
		while (isspace(c));
		if (c < 0)
			break;
		if (!isxdigit(c)) {
inv_input:		fprintf(stderr, "%s: invalid hex file input\n",
				filename);
			fclose(inf);
			return(-1);
		}
		c2 = getc(inf);
		if (!isxdigit(c2))
			goto inv_input;
		if (count >= 255) {
			fprintf(stderr, "%s: hex input data is too long\n",
				filename);
			fclose(inf);
			return(-1);
		}
		databuf[count] = (decode_hex_digit(c) << 4) |
				 decode_hex_digit(c2);
	}
	fclose(inf);
	if (!count) {
		fprintf(stderr, "%s: no hex data input found\n", filename);
		return(-1);
	}
	return(count);
}

decode_hex_data_from_string(arg, databuf)
	char *arg;
	u_char *databuf;
{
	unsigned count;

	for (count = 0; ; count++) {
		while (isspace(*arg))
			arg++;
		if (!*arg)
			break;
		if (!isxdigit(arg[0]) || !isxdigit(arg[1])) {
			fprintf(stderr, "error: invalid hex string input\n");
			return(-1);
		}
		if (count >= 255) {
			fprintf(stderr, "error: hex input data is too long\n");
			return(-1);
		}
		databuf[count] = (decode_hex_digit(arg[0]) << 4) |
				 decode_hex_digit(arg[1]);
		arg += 2;
	}
	if (!count) {
		fprintf(stderr, "error: empty hex string argument\n");
		return(-1);
	}
	return(count);
}