xref: /csrg-svn/lib/libc/gen/getpass.c (revision 37901)
135669Sbostic /*
235669Sbostic  * Copyright (c) 1988 The Regents of the University of California.
335669Sbostic  * All rights reserved.
435669Sbostic  *
535669Sbostic  * Redistribution and use in source and binary forms are permitted
635669Sbostic  * provided that the above copyright notice and this paragraph are
735669Sbostic  * duplicated in all such forms and that any documentation,
835669Sbostic  * advertising materials, and other materials related to such
935669Sbostic  * distribution and use acknowledge that the software was developed
1035669Sbostic  * by the University of California, Berkeley.  The name of the
1135669Sbostic  * University may not be used to endorse or promote products derived
1235669Sbostic  * from this software without specific prior written permission.
1335669Sbostic  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1435669Sbostic  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1535669Sbostic  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1635669Sbostic  */
1735669Sbostic 
1826559Sdonn #if defined(LIBC_SCCS) && !defined(lint)
19*37901Sbostic static char sccsid[] = "@(#)getpass.c	5.4 (Berkeley) 05/11/89";
2035669Sbostic #endif /* LIBC_SCCS and not lint */
2122094Smckusick 
2235669Sbostic #include <sys/ioctl.h>
2335669Sbostic #include <sys/signal.h>
242017Swnj #include <stdio.h>
252017Swnj 
262017Swnj char *
272017Swnj getpass(prompt)
2835669Sbostic 	char *prompt;
292017Swnj {
302017Swnj 	struct sgttyb ttyb;
3135669Sbostic 	register int ch;
322017Swnj 	register char *p;
3335669Sbostic 	FILE *fp, *outfp;
3435669Sbostic 	long omask;
3535669Sbostic 	int svflagval;
36*37901Sbostic #define	PASSWD_LEN	128
3735669Sbostic 	static char buf[PASSWD_LEN + 1];
382017Swnj 
3935669Sbostic 	/*
4035669Sbostic 	 * read and write to /dev/tty if possible; else read from
4135669Sbostic 	 * stdin and write to stderr.
4235669Sbostic 	 */
4335669Sbostic 	if ((outfp = fp = fopen("/dev/tty", "w+")) == NULL) {
4435669Sbostic 		outfp = stderr;
4535669Sbostic 		fp = stdin;
4635669Sbostic 	}
4735669Sbostic 
4835669Sbostic 	(void)ioctl(fileno(fp), TIOCGETP, &ttyb);
4935669Sbostic 	svflagval = ttyb.sg_flags;
502017Swnj 	ttyb.sg_flags &= ~ECHO;
5135669Sbostic 	omask = sigblock(sigmask(SIGINT));
5235669Sbostic 	(void)ioctl(fileno(fp), TIOCSETP, &ttyb);
5335669Sbostic 
54*37901Sbostic 	(void)fputs(prompt, outfp);
5535669Sbostic 	rewind(outfp);			/* implied flush */
5635669Sbostic 	for (p = buf; (ch = getc(fp)) != EOF && ch != '\n';)
5735669Sbostic 		if (p < buf + PASSWD_LEN)
5835669Sbostic 			*p++ = ch;
592017Swnj 	*p = '\0';
6035669Sbostic 	(void)write(fileno(outfp), "\n", 1);
6135669Sbostic 
6235669Sbostic 	ttyb.sg_flags = svflagval;
6335669Sbostic 	(void)ioctl(fileno(fp), TIOCSETP, &ttyb);
6435669Sbostic 	(void)sigsetmask(omask);
6535669Sbostic 	if (fp != stdin)
6635669Sbostic 		(void)fclose(fp);
6735669Sbostic 	return(buf);
682017Swnj }
69