2001-12-20 17:20:58 +01:00
|
|
|
/* 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"
|
|
|
|
|
2001-12-23 13:40:04 +01:00
|
|
|
#ifdef MKDIR_TAKES_ONE_ARG
|
|
|
|
# undef mkdir
|
|
|
|
# define mkdir(a,b) mkdir(a)
|
|
|
|
#endif
|
|
|
|
|
2001-12-20 17:20:58 +01:00
|
|
|
char *mkdtemp(char *template)
|
|
|
|
{
|
2001-12-22 16:22:59 +01:00
|
|
|
int attempts,idx,count=0;
|
2001-12-20 17:20:58 +01:00
|
|
|
byte *ch;
|
|
|
|
|
2001-12-22 16:22:59 +01:00
|
|
|
idx=strlen(template);
|
|
|
|
|
|
|
|
if(idx==0)
|
|
|
|
{
|
|
|
|
errno=EINVAL;
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
ch=&template[idx-1];
|
2001-12-20 17:20:58 +01:00
|
|
|
|
|
|
|
/* Walk backwards to count all the Xes */
|
2001-12-22 16:22:59 +01:00
|
|
|
while(*ch=='X' && count<idx)
|
2001-12-20 17:20:58 +01:00
|
|
|
{
|
|
|
|
count++;
|
|
|
|
ch--;
|
|
|
|
}
|
|
|
|
|
|
|
|
ch++;
|
|
|
|
|
|
|
|
if(count==0)
|
|
|
|
{
|
|
|
|
errno=EINVAL;
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Try 4 times to make the temp directory */
|
|
|
|
for(attempts=0;attempts<4;attempts++)
|
|
|
|
{
|
2001-12-22 16:22:59 +01:00
|
|
|
int remaining=count;
|
2001-12-20 17:20:58 +01:00
|
|
|
char *marker=ch;
|
|
|
|
byte *randombits;
|
|
|
|
|
2001-12-22 16:22:59 +01:00
|
|
|
idx=0;
|
|
|
|
|
2001-12-20 17:20:58 +01:00
|
|
|
/* 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)
|
|
|
|
{
|
2001-12-22 16:22:59 +01:00
|
|
|
sprintf(marker,"%02X",randombits[idx++]);
|
2001-12-20 17:20:58 +01:00
|
|
|
marker+=2;
|
|
|
|
remaining-=2;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Any leftover Xes? get_random_bits rounds up to full bytes,
|
|
|
|
so this is safe. */
|
|
|
|
if(remaining>0)
|
2001-12-22 16:22:59 +01:00
|
|
|
sprintf(marker,"%X",randombits[idx]&0xF);
|
2001-12-20 17:20:58 +01:00
|
|
|
|
|
|
|
m_free(randombits);
|
|
|
|
|
|
|
|
if(mkdir(template,0700)==0)
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
if(attempts==4)
|
|
|
|
return NULL; /* keeps the errno from mkdir, whatever it is */
|
|
|
|
|
|
|
|
return template;
|
|
|
|
}
|