view calypso/main.c @ 44:0bc89d61fc59

top Makefile: add serial
author Mychaela Falconia <falcon@freecalypso.org>
date Sat, 20 Mar 2021 21:53:31 +0000
parents 2260fbd28b2a
children
line wrap: on
line source

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

static
is_string_all_hex(str)
	char *str;
{
	char *cp;

	for (cp = str; *cp; cp++)
		if (!isxdigit(*cp))
			return(0);
	return(1);
}

cmd_exchange(input)
	char *input;
{
	char *targv[3];
	int rc;

	targv[0] = "X";
	targv[1] = input;
	targv[2] = 0;

	tpinterf_make_cmd(targv);
	rc = tpinterf_send_cmd();
	if (rc < 0)
		return(rc);
	return tpinterf_pass_output(20);
}

cmd_atr()
{
	static char *atr_argv[2] = {"atr", 0};
	int rc;

	tpinterf_make_cmd(atr_argv);
	rc = tpinterf_send_cmd();
	if (rc < 0)
		return(rc);
	return tpinterf_pass_output(1);
}

cmd_poweroff()
{
	static char *poweroff_argv[2] = {"poweroff", 0};

	tpinterf_make_cmd(poweroff_argv);
	tpinterf_send_cmd();
}

main(argc, argv)
	char **argv;
{
	char inbuf[576], *cp;
	unsigned len;

	parse_target_fd_opt(argc, argv);
	set_serial_nonblock(0);
	putchar('\n');
	fflush(stdout);

	for (; fgets(inbuf, sizeof inbuf, stdin); fflush(stdout)) {
		cp = index(inbuf, '\n');
		if (!cp) {
			printf("back end error: missing newline on input\n");
			continue;
		}
		*cp = '\0';
		if (!strcmp(inbuf, "atr")) {
			cmd_atr();
			continue;
		}
		if (!strcmp(inbuf, "poweroff")) {
			cmd_poweroff();
			exit(0);
		}
		if (!is_string_all_hex(inbuf)) {
			printf("back end error: input is not all hex\n");
			continue;
		}
		len = strlen(inbuf);
		if (len & 1) {
			printf(
			"back end error: input has odd number of hex digits\n");
			continue;
		}
		if (len < 10) {
			printf(
		"back end error: input is too short for command APDU\n");
			continue;
		}
		if (len > 520) {
			printf(
			"back end error: input is too long for command APDU\n");
			continue;
		}
		cmd_exchange(inbuf);
	}

	exit(0);
}