2016-04-28 18:15:18 -07:00
|
|
|
#include <arpa/inet.h>
|
|
|
|
#include <sys/socket.h>
|
2016-04-29 06:05:08 -07:00
|
|
|
#include <fcntl.h>
|
2016-04-28 18:15:18 -07:00
|
|
|
#include <assert.h>
|
2016-05-05 16:57:29 -07:00
|
|
|
#include <stdlib.h>
|
2016-04-28 18:15:18 -07:00
|
|
|
|
2016-05-05 16:57:29 -07:00
|
|
|
#define TREZOR_UDP_PORT 21324
|
2016-04-28 18:15:18 -07:00
|
|
|
|
|
|
|
static int s;
|
|
|
|
static struct sockaddr_in si_me, si_other;
|
|
|
|
static socklen_t slen = 0;
|
|
|
|
|
|
|
|
void msg_init(void)
|
|
|
|
{
|
2016-04-29 06:05:08 -07:00
|
|
|
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
2016-04-28 18:15:18 -07:00
|
|
|
assert(s != -1);
|
|
|
|
|
2016-04-29 06:05:08 -07:00
|
|
|
fcntl(s, F_SETFL, O_NONBLOCK);
|
|
|
|
|
2016-04-28 18:15:18 -07:00
|
|
|
si_me.sin_family = AF_INET;
|
2016-05-05 16:57:29 -07:00
|
|
|
const char *ip = getenv("TREZOR_UDP_IP");
|
|
|
|
if (ip) {
|
|
|
|
si_me.sin_addr.s_addr = inet_addr(ip);
|
|
|
|
} else {
|
|
|
|
si_me.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
|
|
|
}
|
|
|
|
const char *port = getenv("TREZOR_UDP_PORT");
|
|
|
|
if (port) {
|
|
|
|
si_me.sin_port = htons(atoi(port));
|
|
|
|
} else {
|
|
|
|
si_me.sin_port = htons(TREZOR_UDP_PORT);
|
|
|
|
}
|
2016-04-28 18:15:18 -07:00
|
|
|
|
|
|
|
int b;
|
|
|
|
b = bind(s, (struct sockaddr*)&si_me, sizeof(si_me));
|
|
|
|
assert(b != -1);
|
|
|
|
}
|
|
|
|
|
2016-05-23 08:53:42 -07:00
|
|
|
ssize_t msg_recv(uint8_t *iface, uint8_t *buf, size_t len)
|
2016-04-28 18:15:18 -07:00
|
|
|
{
|
|
|
|
struct sockaddr_in si;
|
2016-05-18 10:27:42 -07:00
|
|
|
socklen_t sl = sizeof(si);
|
2016-05-23 08:53:42 -07:00
|
|
|
memset(buf, 0, len);
|
2016-08-08 07:39:30 -07:00
|
|
|
*iface = 0; // UDP uses always interface 0
|
2016-05-30 07:29:06 -07:00
|
|
|
ssize_t r = recvfrom(s, buf, len, MSG_DONTWAIT, (struct sockaddr *)&si, &sl);
|
2016-05-23 08:53:42 -07:00
|
|
|
if (r < 0) {
|
|
|
|
return r;
|
2016-04-28 18:15:18 -07:00
|
|
|
}
|
|
|
|
si_other = si;
|
|
|
|
slen = sl;
|
2016-05-23 08:53:42 -07:00
|
|
|
return r;
|
2016-04-28 18:15:18 -07:00
|
|
|
}
|
|
|
|
|
2016-05-23 08:53:42 -07:00
|
|
|
ssize_t msg_send(uint8_t iface, const uint8_t *buf, size_t len)
|
2016-04-28 18:15:18 -07:00
|
|
|
{
|
2016-05-23 08:53:42 -07:00
|
|
|
(void)iface; // ignore interface for UDP
|
2016-10-04 09:53:32 -07:00
|
|
|
ssize_t r = len;
|
|
|
|
if (slen > 0) {
|
2016-04-28 18:15:18 -07:00
|
|
|
r = sendto(s, buf, len, MSG_DONTWAIT, (const struct sockaddr *)&si_other, slen);
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
|
|
|
// from modtrezorui:
|
2016-10-03 10:56:45 -07:00
|
|
|
uint32_t trezorui_poll_event(void);
|
2016-04-28 18:15:18 -07:00
|
|
|
|
2016-10-03 10:56:45 -07:00
|
|
|
#define msg_poll_ui_event trezorui_poll_event
|