summaryrefslogtreecommitdiffstats
path: root/gpglib/tempname.c
blob: 3112d33962185551105dd36d1c3a37c98e60180e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
** Copyright 2001-2003 Double Precision, Inc.  See COPYING for
** distribution information.
*/


#include "config.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <sys/time.h>
#include "tempname.h"

static const char base64[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-,";

int libmail_tempfile(char *filename_buf)
{
	unsigned long seed;
	int i;
	int fd;

#if HAVE_GETTIMEOFDAY
	struct timeval tv;

	gettimeofday(&tv, NULL);

	seed=tv.tv_sec;
	seed ^= tv.tv_usec << 16;
#else
	time_t t;

	time(&t);
	seed=t;
#endif
	seed ^= getpid();

	for (i=0; i<1000; i++, seed += 5000)
	{
		char *p;
		unsigned long n;

		strcpy(filename_buf, "/tmp/mimegpg.");

		p=filename_buf + strlen(filename_buf);

		n=seed;
		*p++=base64[ n % 64 ]; n /= 64;
		*p++=base64[ n % 64 ]; n /= 64;
		*p++=base64[ n % 64 ]; n /= 64;
		*p++=base64[ n % 64 ]; n /= 64;
		*p++=base64[ n % 64 ]; n /= 64;
		*p++=base64[ n % 64 ];
		*p=0;

		if ((fd=open(filename_buf, O_RDWR | O_CREAT | O_EXCL, 0600))
		    >= 0)
			return (fd);


		if (errno != EEXIST)
			break;
	}
	return (-1);
}