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#include <sys/types.h>
13#include <sys/stat.h>
14#include <fcntl.h>
15#include <errno.h>
16#include <boost/filesystem/path.hpp>
17
18#include "cryptopp/osrng.h"
19#include "file_io.hh"
20
21#ifndef O_BINARY
22#define O_BINARY 0
23#endif
24
25int
26monotone_mkstemp(std::string &tmpl)
27{
28 unsigned int len = 0;
29 int i = 0;
30 int count = 0, fd = -1;
31 std::string tmp;
32 fs::path path;
33
34 static const char letters[] =
35 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
36 static const int NLETTERS = sizeof (letters) - 1;
37 static CryptoPP::AutoSeededRandomPool mkstemp_urandom;
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[mkstemp_urandom.GenerateByte() % NLETTERS]);
49 fd = open(tmp.c_str(), O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
50 if (fd >= 0)
51 {
52fs::path path;
53path = mkpath(tmp);
54tmpl = path.native_directory_string();
55return fd;
56 }
57 else if (errno != EEXIST)
58break;
59 }
60 return -1;
61}
62

Archive Download this file

Branches

Tags

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