-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplatform-unix.c
127 lines (103 loc) · 2.08 KB
/
platform-unix.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2023 SASANO Takayoshi <[email protected]>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include "platform.h"
char *serdev = NULL;
char *keystr = NULL;
static int fd = -1;
#define SIGNDEV_SERIAL_SPEED B9600
int platform_setup(int argc, char *argv[])
{
int ch;
while ((ch = getopt(argc, argv, "l:k:")) != -1) {
switch (ch) {
case 'l':
serdev = optarg;
break;
case 'k':
keystr = optarg;
break;
}
}
#ifdef NSDEMU_TEST
#define check_arg (serdev == NULL)
#define option_keystr ""
#else
#define check_arg ((serdev == NULL) || (keystr == NULL))
#define option_keystr " -k [secure key]"
#endif
if (check_arg) {
printf("usage: %s -l [serial device]"
option_keystr "\n", argv[0]);
return -1;
}
return 0;
}
int platform_finish(void)
{
return 0;
}
void random_engine_initialize(void)
{
/* do nothing */
}
void random_fill_buf(void *buf, int len)
{
arc4random_buf(buf, len);
}
char serial_read_char(void)
{
char c = 0;
ssize_t size;
/* not good, but enough to test */
while (fd >= 0 && (size = read(fd, &c, sizeof(c))) < 1)
usleep(10000);
return c;
}
void serial_send_buffer(const void *buf, int len)
{
write(fd, buf, len);
}
void serial_send_string(const char *str)
{
serial_send_buffer(str, strlen(str));
}
int serial_open(const char *arg)
{
struct termios t;
int flags, v = -1;
/* device is non-blocked during setup */
if ((fd = open(arg, O_RDWR | O_NOCTTY | O_EXCL | O_NONBLOCK)) < 0)
goto fin0;
memset(&t, 0, sizeof(t));
cfsetospeed(&t, SIGNDEV_SERIAL_SPEED);
cfsetispeed(&t, SIGNDEV_SERIAL_SPEED);
t.c_cflag |= CREAD | CLOCAL | CS8;
// t.c_cflag |= CRTSCTS;
t.c_iflag = INPCK;
t.c_oflag = 0;
t.c_lflag = 0;
t.c_cc[VTIME] = 0;
t.c_cc[VMIN] = 1;
tcflush(fd, TCIOFLUSH);
tcsetattr(fd, TCSANOW, &t);
if ((flags = fcntl(fd, F_GETFL)) < 0 ||
fcntl(fd, F_SETFL, (flags & ~O_NONBLOCK)) < 0)
goto fin1;
v = 0;
goto fin0;
fin1:
serial_close();
fin0:
return v;
}
void serial_close(void)
{
close(fd);
fd = -1;
}