changeset 3230:d05dc05bde8a

[gaim-migrate @ 3247] Added gaim_mkstemp() for secure tempfile creation. committer: Tailor Script <tailor@pidgin.im>
author Jim Seymour <jseymour>
date Tue, 07 May 2002 23:12:14 +0000
parents 20612da83d8c
children b913fc07e18a
files src/gaim.h src/util.c
diffstat 2 files changed, 48 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/gaim.h	Tue May 07 00:51:15 2002 +0000
+++ b/src/gaim.h	Tue May 07 23:12:14 2002 +0000
@@ -432,6 +432,7 @@
 extern char *add_cr(char *);
 extern void strip_linefeed(char *);
 extern time_t get_time(int, int, int, int, int, int);
+extern FILE *gaim_mkstemp(gchar **);
 
 /*------------------------------------------------------------------------*/
 /*  Multi-Entry dialog and vCard dialog support                           */
--- a/src/util.c	Tue May 07 00:51:15 2002 +0000
+++ b/src/util.c	Tue May 07 23:12:14 2002 +0000
@@ -1266,3 +1266,50 @@
 	tm.tm_sec = sec >= 0 ? sec : time(NULL) % 60;
 	return mktime(&tm);
 }
+
+/*
+ * Like mkstemp() but returns a file pointer, uses a pre-set template,
+ * uses the semantics of tempnam() for the directory to use and allocates
+ * the space for the filepath.
+ *
+ * Caller is responsible for closing the file and removing it when done,
+ * as well as freeing the space pointed-to by "path" with g_free().
+ *
+ * Returns NULL on failure and cleans up after itself if so.
+ */
+static const char *gaim_mkstemp_templ = {"gaimXXXXXX"};
+
+FILE *gaim_mkstemp(gchar **fpath)
+{
+	static char *tmpdir = NULL;
+	int fd;
+	FILE *fp = NULL;
+
+	if(!tmpdir) {
+		if((tmpdir = tempnam(NULL, NULL)) == NULL) {
+			fprintf(stderr, "tempnam() failed, error: %d\n", errno);
+		} else {
+			char *t = strrchr(tmpdir, '/');
+			*t = '\0';
+		}
+	}
+
+	if(tmpdir) {
+		if((*fpath = g_strdup_printf("%s/%s", tmpdir, gaim_mkstemp_templ)) != NULL) {
+			if((fd = mkstemp(*fpath)) == -1) {
+				fprintf(stderr, "Couldn't make \"%s\", error: %d\n", *fpath, errno);
+			} else {
+				if((fp = fdopen(fd, "r+")) == NULL) {
+					close(fd);
+					fprintf(stderr, "Couldn't fdopen(), error: %d\n", errno);
+				}
+			}
+			if(!fp) {
+				g_free(*fpath);
+				*fpath = NULL;
+			}
+		}
+	}
+
+	return fp;
+}