monotone

monotone Mtn Source Tree

Root/mkstemp.cc

1
2// this is a somewhat more portable mkstemp which uses the system prng to
3// seed. from what I've seen on other system mkstemps, they are usually
4// *worse* than this (or non-existant).
5//
6// the source is partially cribbed from gfileutils.c in glib, which is
7// copyright (c) 2000 Red Hat. It was released as LGPL, so I have copied
8// some of its text into this file and am relicensing my derivative work
9// (this file) copyright (C) 2004 graydon hoare, as LGPL also.
10
11#include "config.h"
12
13#include <sys/types.h>
14#include <sys/stat.h>
15#include <fcntl.h>
16#include <errno.h>
17#include <unistd.h>
18
19#include "botan/botan.h"
20
21#ifndef O_BINARY
22#define O_BINARY 0
23#endif
24
25using std::string;
26
27bool
28monotone_mkstemp(string &tmpl)
29{
30 unsigned int len = 0;
31 int i = 0;
32 int count = 0, fd = -1;
33 string tmp;
34
35 static const char letters[] =
36 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
37 static const int NLETTERS = sizeof (letters) - 1;
38
39 len = tmpl.length();
40 if (len < 6 || tmpl.rfind("XXXXXX") != len-6)
41 return -1;
42
43 for (count = 0; count < 100; ++count)
44 {
45 tmp = tmpl.substr(0, len-6);
46
47 for (i = 0; i < 6; ++i)
48 tmp.append(1, letters[Botan::Global_RNG::random() % NLETTERS]);
49#ifdef _MSC_VER
50 fd = _open(tmp.c_str(), _O_RDWR | _O_CREAT | _O_EXCL | _O_BINARY, 0600);
51#else
52 fd = open(tmp.c_str(), O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
53#endif
54 if (fd >= 0)
55 {
56 tmpl = tmp;
57#ifdef _MSC_VER
58 _close(fd);
59#else
60 close(fd);
61#endif
62 return true;
63 }
64 else if (errno != EEXIST)
65 break;
66 }
67 return false;
68}
69
70
71// Local Variables:
72// mode: C++
73// fill-column: 76
74// c-file-style: "gnu"
75// indent-tabs-mode: nil
76// End:
77// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status