Back to index

courier  0.68.2
comtmpfile2.c
Go to the documentation of this file.
00001 /*
00002 ** Copyright 1998 - 2001 Double Precision, Inc.
00003 ** See COPYING for distribution information.
00004 */
00005 
00006 #include      "courier_lib_config.h"
00007 #include      "courier.h"
00008 #if    HAVE_SYS_STAT_H
00009 #include      <sys/stat.h>
00010 #endif
00011 #if    HAVE_UNISTD_H
00012 #include      <unistd.h>
00013 #endif
00014 #include      <stdlib.h>
00015 #include      <string.h>
00016 #include      <errno.h>
00017 #include      <stdio.h>
00018 #include      <fcntl.h>
00019 #include      <time.h>
00020 #if TIME_WITH_SYS_TIME
00021 #include      <sys/time.h>
00022 #include      <time.h>
00023 #else
00024 #if HAVE_SYS_TIME_H
00025 #include      <sys/time.h>
00026 #else
00027 #include      <time.h>
00028 #endif
00029 #endif
00030 
00031 static const char base64[] =
00032 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-,";
00033 
00034 char *mktmpfilename()
00035 {
00036        unsigned long seed;
00037        int i;
00038        int fd;
00039        char filename_buf[64];
00040 
00041 #if HAVE_GETTIMEOFDAY
00042        struct timeval tv;
00043 
00044        gettimeofday(&tv, NULL);
00045 
00046        seed=tv.tv_sec;
00047        seed ^= tv.tv_usec << 16;
00048 #else
00049        time_t t;
00050 
00051        time(&t);
00052        seed=t;
00053 #endif
00054        seed ^= getpid();
00055 
00056        for (i=0; i<1000; i++, seed += 5000)
00057        {
00058               char *p;
00059               unsigned long n;
00060 
00061               strcpy(filename_buf, "/tmp/courier.");
00062 
00063               p=filename_buf + strlen(filename_buf);
00064 
00065               n=seed;
00066               *p++=base64[ n % 64 ]; n /= 64;
00067               *p++=base64[ n % 64 ]; n /= 64;
00068               *p++=base64[ n % 64 ]; n /= 64;
00069               *p++=base64[ n % 64 ]; n /= 64;
00070               *p++=base64[ n % 64 ]; n /= 64;
00071               *p++=base64[ n % 64 ];
00072               *p=0;
00073 
00074               if ((fd=open(filename_buf, O_RDWR | O_CREAT | O_EXCL, 0600))
00075                   >= 0)
00076               {
00077                      char *p;
00078 
00079                      close(fd);
00080 
00081                      p=strdup(filename_buf);
00082                      if (!p)
00083                             unlink(filename_buf);
00084                      return (p);
00085               }
00086 
00087               if (errno != EEXIST)
00088                      break;
00089        }
00090        return (NULL);
00091 }