#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <io.h>
#include <bios.h>
#include <dos.h>

static int getkey(int);

void
ruserpass(host, pname, ppass)
char *host;
char **pname;
char **ppass;
{
	static char name[32];
	static char pass[16];
	FILE *in = fopen("con", "rt");
	FILE *out = fopen("con", "wt");
	int c;
	char *cp, *user;

	if (!in)
		in = stdin;
	if (!out)
		out = stderr;
	if (*pname == 0) {
		user = getenv("USER");
		if (user)
			fprintf(out, "Name (%s:%s): ", host, user);
		else
			fprintf(out, "Name (%s:): ", host);
		fflush(out);
		name[0] = sizeof name - 2;
		fgets(name, sizeof name, in);
		cp = strchr(name, '\n');
		if (cp)
			*cp = 0;
		if (user && name[0] == 0)
			strcpy(name, user);
		*pname = name;
	}
	if (*ppass == 0) {
		fprintf(out, "Password (%s:%s): ", host, *pname);
		fflush(out);
		user = pass;
		for (;;) {
			c = getkey(fileno(in));
			if (c == EOF)
				goto out;
			*user = (char)c;
			if (*user == '\b') {
				if (user > pass)
					user--;
				continue;
			}
			if (*user == '\r' || *user == '\n') {
				*user = 0;
				putc('\n', out);
				fflush(out);
				break;
			}
			user++;
		}
out:
		*ppass = pass;
	}
	if (in != stdin)
		fclose(in);
	if (out != stderr)
		fclose(out);
}

static int
getkey(fd)
int fd;
{
	unsigned char c;
	int n;
	union REGS regs;

	regs.h.ah = 0x44;	/* IOCTL */
	regs.h.al = 0x00;	/* get flags */
	regs.x.bx = fd;
	intdos(&regs, &regs);

	regs.h.ah = 0x44;	/* IOCTL */
	regs.h.al = 0x01;	/* set flags */
	regs.h.dh = 0;
	regs.h.dl |= 0x20;	/* set RAW bit */
	intdos(&regs, &regs);

	_dos_read(fd, &c, 1, &n);

	regs.h.ah = 0x44;	/* IOCTL */
	regs.h.al = 0x01;	/* set flags */
	regs.h.dl &= ~0x20;	/* clear RAW bit */
	intdos(&regs, &regs);
	if (n != 1)
		return -1;
	return (int)c;
}
