-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathtempdir.c
75 lines (64 loc) · 1.61 KB
/
tempdir.c
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
/*
* notion/ioncore/tempdir.c
*
* Copyright (c) 2019 The Notion development team
*
* See the included file LICENSE for details.
*/
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L /* mkdtemp(3) */
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <dirent.h>
#include <stddef.h>
#include "tempdir.h"
#include "log.h"
static char template[]="/tmp/notion.XXXXXX\0\0";
static char const *tempdir=NULL;
/*EXTL_DOC
* Returns the global temporary directory for this notion instance with a
* trailing slash. The directory is created in case it does not exist.
* The directory will be non-recursively deleted on teardown, therefore no
* subdirectories should be created.
*/
EXTL_SAFE
EXTL_EXPORT
const char *ioncore_tempdir()
{
if(tempdir)
return tempdir;
tempdir=mkdtemp(template); /* points to template */
if(!tempdir){
LOG(ERROR, GENERAL, "Error creating temporary directory: %s.",
strerror(errno));
return NULL;
}
template[strlen(tempdir)]='/';
return tempdir;
}
void ioncore_tempdir_cleanup(void)
{
DIR *dir;
struct dirent *dent;
char fname[sizeof(template)+NAME_MAX];
size_t const offs=strlen(template);
if(!tempdir)
return;
dir=opendir(tempdir);
if(!dir){
LOG(ERROR, GENERAL, "Error opening temporary directory: %s.",
strerror(errno));
return;
}
strcpy(fname, tempdir);
while((dent=readdir(dir))){
strcpy(fname+offs, dent->d_name);
unlink(fname);
}
closedir(dir);
rmdir(tempdir);
tempdir=NULL;
}