- Move setting _U_ into config.h, because
[obnox/wireshark/wip.git] / tempfile.c
index d82a3d392424696c53fded21cd346ebaa0b55ed2..5f19b78d50bd82bca6000be3449f422069fc8de5 100644 (file)
@@ -3,8 +3,8 @@
  *
  * $Id$
  *
- * Ethereal - Network traffic analyzer
- * By Gerald Combs <gerald@ethereal.com>
+ * Wireshark - Network traffic analyzer
+ * By Gerald Combs <gerald@wireshark.org>
  * Copyright 1998 Gerald Combs
  *
  * This program is free software; you can redistribute it and/or
 
 #include <glib.h>
 
+#include <time.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
 #include <errno.h>
 
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
 #endif
 
-#include "file_util.h"
-
-#if GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 6)
-#include <glib/gstdio.h>       /* available since GLib 2.6 only! */
-
-/* GLib2.6 or above, using new wrapper functions */
-#define eth_mkstemp g_mkstemp
-#else
-#define eth_mkstemp mkstemp
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
 #endif
 
-/*
- * This has to come after the include of <pcap.h>, as the include of
- * <pcap.h> might cause <winsock2.h> to be included, and if we've
- * already included <winsock.h> as a result of including <windows.h>,
- * we get a bunch of redefinitions.
- */
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
 
+#ifdef _WIN32
+#include <process.h>    /* For getpid() */
+#endif
+
 #include "tempfile.h"
+#include <wsutil/file_util.h>
+
+#ifndef __set_errno
+#define __set_errno(x) errno=(x)
+#endif
 
-static const char *
-setup_tmpdir(const char *dir)
+#define INITIAL_PATH_SIZE   128
+#define TMP_FILE_SUFFIX     "XXXXXX"
+
+#ifndef HAVE_MKSTEMP
+/* Generate a unique temporary file name from TEMPLATE.
+   The last six characters of TEMPLATE must be TMP_FILE_SUFFIX;
+   they are replaced with a string that makes the filename unique.
+   Returns a file descriptor open on the file for reading and writing.  */
+static int
+mkstemp (char *template)
 {
-       size_t len = strlen(dir);
-       char *newdir;
+  static const char letters[]
+    = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+  size_t len;
+  size_t i;
 
-       /* Append path separator if necessary */
-       if (len != 0 && dir[len - 1] == G_DIR_SEPARATOR) {
-               return dir;
-       }
-       else {
-               newdir = g_malloc(len + 2);
-               strcpy(newdir, dir);
-               strcat(newdir, G_DIR_SEPARATOR_S);
-               return newdir;
-       }
+  len = strlen (template);
+  if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX))
+    {
+      __set_errno (EINVAL);
+      return -1;
+    }
+
+  if (g_snprintf (&template[len - 5], 6, "%.5u",
+              (unsigned int) getpid () % 100000) != 5)
+    /* Inconceivable lossage.  */
+    return -1;
+
+  for (i = 0; i < sizeof (letters); ++i)
+    {
+      int fd;
+
+      template[len - 6] = letters[i];
+
+      fd = ws_open (template, O_RDWR|O_BINARY|O_CREAT|O_EXCL, 0600);
+      if (fd >= 0)
+       return fd;
+    }
+
+  /* We return the null string if we can't find a unique file name.  */
+
+  template[0] = '\0';
+  return -1;
 }
 
-static int
-try_tempfile(char *namebuf, int namebuflen, const char *dir, const char *pfx)
+#endif /* HAVE_MKSTEMP */
+
+#ifndef HAVE_MKDTEMP
+/* Generate a unique temporary directory name from TEMPLATE.
+   The last six characters of TEMPLATE must be TMP_FILE_SUFFIX;
+   they are replaced with a string that makes the filename unique.
+   Returns 0 on success or -1 on error (from mkdir(2)).  */
+char *
+mkdtemp (char *template)
 {
-       static const char suffix[] = "XXXXXXXXXX";
-       int namelen = strlen(dir) + strlen(pfx) + sizeof suffix;
+  static const char letters[]
+    = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+  size_t len;
+  size_t i;
+
+  len = strlen (template);
+  if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX))
+    {
+      __set_errno (EINVAL);
+      return NULL;
+    }
+
+  if (g_snprintf (&template[len - 5], 6, "%.5u",
+              (unsigned int) getpid () % 100000) != 5)
+    /* Inconceivable lossage.  */
+    return NULL;
+
+  for (i = 0; i < sizeof (letters); ++i)
+    {
+      int ret;
+
+      template[len - 6] = letters[i];
+
+      ret = ws_mkdir(template, 0700);
+      if (ret >= 0)
+       return template;
+    }
+
+  /* We return the null string if we can't find a unique file name.  */
+
+  template[0] = '\0';
+  return NULL;
+}
+
+#endif /* HAVE_MKDTEMP */
+
+#define MAX_TEMPFILES   3
+
+/**
+ * Create a tempfile with the given prefix (e.g. "wireshark").
+ * 
+ * @param namebuf If not NULL, receives the full path of the temp file.
+ *                Should NOT be freed.
+ * @param pfx A prefix for the temporary file.
+ * @return The file descriptor of the new tempfile, from mkstemp().
+ */
+int
+create_tempfile(char **namebuf, const char *pfx)
+{
+       static struct _tf {
+               char *path;
+               unsigned long len;
+       } tf[MAX_TEMPFILES];
+       static int idx;
+
+       const char *tmp_dir;
        int old_umask;
-       int tmp_fd;
-
-       if (namebuflen < namelen) {
-               /* Stick in a truncated name, so that if this error is
-                  reported with the file name, you at least get
-                  something. */
-               g_snprintf(namebuf, namebuflen, "%s%s%s", dir, pfx, suffix);
-               errno = ENAMETOOLONG;
-               return -1;
+       int fd;
+       time_t current_time;
+       char timestr[14 + 1];
+       gchar *tmp_file;
+       gchar sep[2] = {0, 0};
+
+       idx = (idx + 1) % MAX_TEMPFILES;
+       
+       /*
+        * Allocate the buffer if it's not already allocated.
+        */
+       if (tf[idx].path == NULL) {
+               tf[idx].len = INITIAL_PATH_SIZE;
+               tf[idx].path = (char *)g_malloc(tf[idx].len);
+       }
+
+       /*
+        * We can't use get_tempfile_path here because we're called from dumpcap.c.
+        */
+       tmp_dir = g_get_tmp_dir();
+
+#ifdef _WIN32
+       _tzset();
+#endif
+       current_time = time(NULL);
+       strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
+       sep[0] = G_DIR_SEPARATOR;
+       tmp_file = g_strconcat(tmp_dir, sep, pfx, "_", timestr, "_", TMP_FILE_SUFFIX, NULL);
+       if (strlen(tmp_file) > tf[idx].len) {
+               tf[idx].len = (int)strlen(tmp_file) + 1;
+               tf[idx].path = (char *)g_realloc(tf[idx].path, tf[idx].len);
        }
-       strcpy(namebuf, dir);
-       strcat(namebuf, pfx);
-       strcat(namebuf, suffix);
+       g_strlcpy(tf[idx].path, tmp_file, tf[idx].len);
+       g_free(tmp_file);
 
+       if (namebuf) {
+               *namebuf = tf[idx].path;
+       }
        /* The Single UNIX Specification doesn't say that "mkstemp()"
           creates the temporary file with mode rw-------, so we
           won't assume that all UNIXes will do so; instead, we set
@@ -105,57 +214,50 @@ try_tempfile(char *namebuf, int namebuflen, const char *dir, const char *pfx)
           permissions, attempt to create the file, and then put
           the umask back. */
        old_umask = umask(0077);
-       tmp_fd = eth_mkstemp(namebuf);
+       fd = mkstemp(tf[idx].path);
        umask(old_umask);
-       return tmp_fd;
+       return fd;
 }
 
-static const char *tmpdir = NULL;
-#ifdef _WIN32
-static const char *temp = NULL;
-#endif
-static const char *E_tmpdir;
-
-#ifndef P_tmpdir
-#define P_tmpdir "/var/tmp"
-#endif
-
-int
-create_tempfile(char *namebuf, int namebuflen, const char *pfx)
+/**
+ * Create a directory with the given prefix (e.g. "wireshark"). The path
+ * is created using g_get_tmp_dir and mkdtemp.
+ * 
+ * @param namebuf 
+ * @param pfx A prefix for the temporary directory.
+ * @return The temporary directory path on success, or NULL on failure.
+ *         Must NOT be freed.
+ */
+const char *
+create_tempdir(char **namebuf, const char *pfx)
 {
-       char *dir;
-       int fd;
-       static gboolean initialized;
+       static char *td_path[3];
+       static int td_path_len[3];
+       static int idx;
+       const char *tmp_dir;
 
-       if (!initialized) {
-               if ((dir = getenv("TMPDIR")) != NULL)
-                       tmpdir = setup_tmpdir(dir);
-#ifdef _WIN32
-               if ((dir = getenv("TEMP")) != NULL)
-                       temp = setup_tmpdir(dir);
-#endif
-
-               E_tmpdir = setup_tmpdir(P_tmpdir);
-               initialized = TRUE;
+       idx = (idx + 1) % 3;
+       
+       /*
+        * Allocate the buffer if it's not already allocated.
+        */
+       if (td_path[idx] == NULL) {
+               td_path_len[idx] = INITIAL_PATH_SIZE;
+               td_path[idx] = (char *)g_malloc(td_path_len[idx]);
        }
 
-       if (tmpdir != NULL) {
-               fd = try_tempfile(namebuf, namebuflen, tmpdir, pfx);
-               if (fd != -1)
-                       return fd;
-       }
+       /*
+        * We can't use get_tempfile_path here because we're called from dumpcap.c.
+        */
+       tmp_dir = g_get_tmp_dir();
 
-#ifdef _WIN32
-       if (temp != NULL) {
-               fd = try_tempfile(namebuf, namebuflen, temp, pfx);
-               if (fd != -1)
-                       return fd;
+       while (g_snprintf(td_path[idx], td_path_len[idx], "%s%c%s" TMP_FILE_SUFFIX, tmp_dir, G_DIR_SEPARATOR, pfx) > td_path_len[idx]) {
+               td_path_len[idx] *= 2;
+               td_path[idx] = (char *)g_realloc(td_path[idx], td_path_len[idx]);
        }
-#endif
-
-       fd = try_tempfile(namebuf, namebuflen, E_tmpdir, pfx);
-       if (fd != -1)
-               return fd;
 
-       return try_tempfile(namebuf, namebuflen, G_DIR_SEPARATOR_S "tmp", pfx);
+       if (namebuf) {
+               *namebuf = td_path[idx];
+       }
+       return mkdtemp(td_path[idx]);
 }