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
12#include "base.hh"
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 <boost/shared_ptr.hpp>
20#include "botan/rng.h"
21
22#ifndef O_BINARY
23#define O_BINARY 0
24#endif
25
26using std::string;
27
28bool
29monotone_mkstemp(string &tmpl)
30{
31 unsigned int len = 0;
32 int i = 0;
33 int count = 0, fd = -1;
34 string tmp;
35
36 boost::shared_ptr<Botan::RandomNumberGenerator> rng(
37 Botan::RandomNumberGenerator::make_rng());
38
39 static const char letters[] =
40 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
41 static const int NLETTERS = sizeof (letters) - 1;
42
43 len = tmpl.length();
44 if (len < 6 || tmpl.rfind("XXXXXX") != len-6)
45 return -1;
46
47 for (count = 0; count < 100; ++count)
48 {
49 tmp = tmpl.substr(0, len-6);
50
51 for (i = 0; i < 6; ++i)
52 tmp.append(1, letters[rng->next_byte() % NLETTERS]);
53#ifdef _MSC_VER
54 fd = _open(tmp.c_str(), _O_RDWR | _O_CREAT | _O_EXCL | _O_BINARY, 0600);
55#else
56 fd = open(tmp.c_str(), O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
57#endif
58 if (fd >= 0)
59 {
60 tmpl = tmp;
61#ifdef _MSC_VER
62 _close(fd);
63#else
64 close(fd);
65#endif
66 return true;
67 }
68 else if (errno != EEXIST)
69 break;
70 }
71 return false;
72}
73
74
75// Local Variables:
76// mode: C++
77// fill-column: 76
78// c-file-style: "gnu"
79// indent-tabs-mode: nil
80// End:
81// 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