magidoor/MD_Getc.c
Andrew Pamment 18a23222a9 fixes
2021-03-12 19:14:22 +10:00

140 lines
3.1 KiB
C

#include <errno.h>
#include <stdio.h>
#if defined(_MSC_VER) || defined(WIN32)
#include <winsock2.h>
#define STDIN_FILENO 1
#else
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <time.h>
#include <string.h>
#include "MagiDoor.h"
#define IAC 255
extern time_t mdtimeout;
extern time_t mdtimeremaining;
char md_getc() {
char c;
int ret;
int stage = 0;
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);
}
#if defined(_MSC_VER)
Sleep(1);
#else
usleep(100);
#endif
continue;
}
else if (ret < 0) {
md_exit(0);
}
if (mdcontrol.socket != -1) {
if ((unsigned char)c == IAC && stage == 0) {
stage = 1;
continue;
}
if (stage == 1) {
if ((unsigned char)c == IAC) {
stage = 0;
} else if ((unsigned char)c == 250) {
stage = 3;
continue;
} else {
stage = 2;
continue;
}
}
if (stage == 2) {
stage = 0;
continue;
}
if (stage == 3) {
if ((unsigned char)c == 240) {
stage = 0;
}
continue;
}
}
mdtimeout = time(NULL) + 900;
return c;
}
}
char md_get_answer(char *options) {
char c;
c = md_getc();
while (strchr(options, c) == NULL) {
c = md_getc();
}
return c;
}
int md_getstring(char *ptr, int maxlen, char minchar, char maxchar) {
char c;
int len = 0;
static char lastc = 'x';
*ptr = '\0';
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("\b \b");
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;
}