File: mkdtemp.c

package info (click to toggle)
gnupg 1.4.18-7+deb8u5
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 34,476 kB
  • sloc: ansic: 127,074; sh: 7,535; asm: 4,610; makefile: 1,186; yacc: 291; perl: 196; pascal: 72; sed: 16
file content (97 lines) | stat: -rw-r--r-- 2,343 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* mkdtemp.c - libc replacement function
 * Copyright (C) 2001 Free Software Foundation, Inc.
 *
 * This file is part of GnuPG.
 *
 * GnuPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * GnuPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

/* This is a replacement function for mkdtemp in case the platform
   we're building on (like mine!) doesn't have it. */

#include <config.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include "types.h"
#include "cipher.h"

#ifdef MKDIR_TAKES_ONE_ARG
# undef mkdir
# define mkdir(a,b) mkdir(a)
#endif

char *mkdtemp(char *template)
{
  unsigned int attempts,idx,count=0;
  char *ch;

  idx=strlen(template);

  /* Walk backwards to count all the Xes */
  while(idx>0 && template[idx-1]=='X')
    {
      count++;
      idx--;
    }

  if(count==0)
    {
      errno=EINVAL;
      return NULL;
    }

  ch=&template[idx];

  /* Try 4 times to make the temp directory */
  for(attempts=0;attempts<4;attempts++)
    {
      unsigned int remaining=count;
      char *marker=ch;
      byte *randombits;

      idx=0;

      /* Using really random bits is probably overkill here.  The
	 worst thing that can happen with a directory name collision
	 is that the function will return an error. */

      randombits=get_random_bits(4*remaining,0,0);

      while(remaining>1)
	{
	  sprintf(marker,"%02X",randombits[idx++]);
	  marker+=2;
	  remaining-=2;
	}

      /* Any leftover Xes?  get_random_bits rounds up to full bytes,
         so this is safe. */
      if(remaining>0)
	sprintf(marker,"%X",randombits[idx]&0xF);

      xfree(randombits);

      if(mkdir(template,0700)==0)
	break;
    }

  if(attempts==4)
    return NULL; /* keeps the errno from mkdir, whatever it is */

  return template;
}