/*	Copyright (c) 1988 AT&T	*/
/*	  All Rights Reserved  	*/

/*	THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T	*/
/*	The copyright notice above does not evidence any   	*/
/*	actual or intended publication of such source code.	*/

/*
 * Copyright (c) 1996-1997, by Sun Microsystems, Inc.
 * All rights reserved.
 */

#pragma ident	"@(#)tmpfile.c	1.20	97/02/12 SMI"	/* SVr4.0 1.12	*/

/*LINTLIBRARY*/

/*
 *	tmpfile - return a pointer to an update file that can be
 *		used for scratch. The file will automatically
 *		go away if the program using it terminates.
 */

#include "synonyms.h"
#include "mtlib.h"
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <thread.h>
#include <synch.h>
#include <sys/stat.h>

static char seed[] = { 'a', 'a', 'a', '\0' };
#ifdef _REENTRANT
static mutex_t seed_lk = DEFAULTMUTEX;
#endif _REENTRANT

#define	XS "\bXXXXXX"		/* a '\b' character is prepended to this */
				/* string to avoid conflicts with names */
				/* generated by tmpnam() */
/*ARGSUSED*/
static FILE *
_common(boolean_t large_file)
{
	char	tfname[L_tmpnam];
	FILE	*p;
	char	*q;
	int	mkret;
	mode_t	current_umask;

	(void) strcpy(tfname, P_tmpdir);
	(void) _mutex_lock(&seed_lk);
	(void) strcat(tfname, seed);
	(void) strcat(tfname, XS);

	q = seed;
	while (*q == 'z')
		*q++ = 'a';
	if (*q != '\0')
		++*q;
	(void) _mutex_unlock(&seed_lk);

#if !defined(_LP64)
	if (large_file == B_TRUE) {
		if ((mkret = mkstemp64(tfname)) == -1)
			return (NULL);
	} else
#endif
		if ((mkret = mkstemp(tfname)) == -1)
			return (NULL);

	(void) unlink(tfname);
	current_umask = umask(0777);
	(void) umask(current_umask);
	(void) fchmod(mkret, 0666 & ~current_umask);
	if ((p = fdopen(mkret, "w+")) == NULL) {
		(void) close(mkret);
		return (NULL);
	}

	return (p);
}

#if !defined(_LP64)
FILE *
tmpfile64(void)
{
	return (_common(B_TRUE));
}
#endif	/* _LP64 */

/*
 * This is a bit confusing -- some explanation is in order.
 *
 * When we're compiled 64-bit, there's no point in distinguishing
 * a "large" file from a "small" file -- they're all "large".
 * The argument we pass to '_common' is ignored -- we always call
 * mkstemp which will just do the right thing for us.
 */
FILE *
tmpfile(void)
{
	return (_common(B_FALSE));
}
