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
17#include "file_io.hh"
18#include "botan/botan.h"
19
20#ifndef O_BINARY
21#define O_BINARY 0
22#endif
23
24int
25monotone_mkstemp(std::string &tmpl)
26{
27 unsigned int len = 0;
28 int i = 0;
29 int count = 0, fd = -1;
30 std::string tmp;
31
32 static const char letters[] =
33 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
34 static const int NLETTERS = sizeof (letters) - 1;
35
36 len = tmpl.length();
37 if (len < 6 || tmpl.rfind("XXXXXX") != len-6)
38 return -1;
39
40 for (count = 0; count < 100; ++count)
41 {
42 tmp = tmpl.substr(0, len-6);
43
44 for (i = 0; i < 6; ++i)
45 tmp.append(1, letters[Botan::Global_RNG::random(Botan::Nonce) % NLETTERS]);
46 fd = open(tmp.c_str(), O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
47 if (fd >= 0)
48 {
49 tmpl = tmp;
50 return fd;
51 }
52 else if (errno != EEXIST)
53 break;
54 }
55 return -1;
56}
57

Archive Download this file

Branches

Tags

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