magidoor/MD_Getc.c
Andrew Pamment e13f7e0777 Bug fixes
2019-12-01 19:36:24 +10:00

85 lines
2.0 KiB
C

#include <errno.h>
#include <stdio.h>
#if defined(_MSC_VER) || defined(WIN32)
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif
#include <unistd.h>
#include <time.h>
#include "MagiDoor.h"
extern time_t mdtimeout;
extern time_t mdtimeremaining;
char md_getc() {
char c;
ssize_t ret;
while (1) {
if (mdcontrol.socket == -1) {
ret = read(STDIN_FILENO, &c, 1);
} else {
ret = recv(mdcontrol.socket, &c, 1, 0);
}
if (ret == 0) {
md_exit(0);
}
#if defined(_MSC_VER) || defined(WIN32)
if (ret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) {
#else
if (ret == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
#endif
if (mdtimeout <= time(NULL)) {
md_printf("\r\nIdle timeout!\r\n");
md_exit(0);
}
if (mdtimeremaining <= time(NULL)) {
md_printf("\r\nOut of time!\r\n");
md_exit(0);
}
usleep(100);
continue;
}
mdtimeout = time(NULL) + 900;
return c;
}
}
int md_getstring(char *ptr, int maxlen, char minchar, char maxchar) {
char c;
int len = 0;
static char lastc = 'x';
while (len < maxlen) {
c = md_getc();
if (c == '\n' || c == '\0') {
lastc = c;
if (lastc == '\r') {
continue;
} else {
return len;
}
}
if (c == '\r') {
lastc = c;
return len;
}
if (c == '\b' || c == 127) {
if (len > 0) {
md_printf("\x1b[D \x1b[D");
len--;
ptr[len] = '\0';
}
lastc = c;
continue;
}
if (c >= minchar && c <= maxchar) {
ptr[len++] = c;
ptr[len] = '\0';
md_putchar(c);
}
lastc = c;
}
return len;
}