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 "file_io.hh"
20#include "botan/botan.h"
21
22#ifndef O_BINARY
23#define O_BINARY 0
24#endif
25
26using std::string;
27
28int
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 static const char letters[] =
37 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
38 static const int NLETTERS = sizeof (letters) - 1;
39
40 len = tmpl.length();
41 if (len < 6 || tmpl.rfind("XXXXXX") != len-6)
42 return -1;
43
44 for (count = 0; count < 100; ++count)
45 {
46 tmp = tmpl.substr(0, len-6);
47
48 for (i = 0; i < 6; ++i)
49 tmp.append(1, letters[Botan::Global_RNG::random(Botan::Nonce) % NLETTERS]);
50#ifdef _MSC_VER
51 fd = _open(tmp.c_str(), _O_RDWR | _O_CREAT | _O_EXCL | _O_BINARY, 0600);
52#else
53 fd = open(tmp.c_str(), O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
54#endif
55 if (fd >= 0)
56 {
57 tmpl = tmp;
58 return fd;
59 }
60 else if (errno != EEXIST)
61 break;
62 }
63 return -1;
64}
65
66
67// Local Variables:
68// mode: C++
69// fill-column: 76
70// c-file-style: "gnu"
71// indent-tabs-mode: nil
72// End:
73// 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