1 /* Copyright (C) 2007  John Whitney
2  *
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation; version 2 of the License.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * Author: John Whitney <jjw@deltup.org>
13  */
14 
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <signal.h>
18 #include <string>
19 #include <vector>
20 #include <list>
21 using namespace std;
22 #include "file.h"
23 #include "system.h"
24 #include <openssl/md5.h>
25 
26 string tmpdir;
27 
28 list<string> tempfiles;
29 char tempname[8] = "/000000";
getTmpFilename()30 string getTmpFilename() {
31   string name = tmpdir+tempname;
32   tempfiles.push_back(name);
33   int i;
34   for (i = 6; tempname[i]=='9'; --i)
35     tempname[i]='0';
36   tempname[i]++;
37   return name;
38 }
39 
doneTmpFile(string t)40 void doneTmpFile(string t) {
41   remove_file(t);
42   list<string>::iterator i = tempfiles.begin();
43   while (i != tempfiles.end()) {
44     list<string>::iterator oldi = i;
45     ++i;
46     if (*oldi == t) tempfiles.erase(oldi);
47   }
48 }
49 
50 
cleanup()51 void cleanup() {
52   if (verbose) printf("cleaning up\n");
53   while (!tempfiles.empty()) {
54     doneTmpFile(tempfiles.front());
55   }
56   rmdir(tmpdir.c_str());
57 }
58 
59 
60 volatile sig_atomic_t already_running = 0;
61 
term_signal(int sig)62 void term_signal(int sig) {
63   if (already_running) return;
64   already_running = 1;
65 
66   cleanup();
67 
68   signal (sig, SIG_DFL);
69   raise (sig);
70 }
71 
72 class init_TmpStore {
73   public:
init_TmpStore()74   init_TmpStore() {
75     char *tmpenv =  getenv("TMPDIR");
76     if (!tmpenv) tmpenv = "/tmp";
77     char *tmptemplate = new char[strlen(tmpenv)+9];
78     strcpy(tmptemplate, tmpenv);
79     strcat(tmptemplate, "/.XXXXXX");
80 
81     tmpdir = mkdtemp(tmptemplate);
82 //  free(tmptemplate);
83 //    printf("%s\n", tmpdir);
84     atexit(cleanup);
85 
86     signal(SIGINT, term_signal);
87     signal(SIGKILL, term_signal);
88     signal(SIGSEGV, term_signal);
89     signal(SIGTERM, term_signal);
90     signal(SIGQUIT, term_signal);
91 //    signal(SIGCONT, term_signal);
92   }
93 } tmpstr;
94