File: TempDirectory.cpp

package info (click to toggle)
sonic-visualiser 5.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 24,640 kB
  • sloc: cpp: 158,888; ansic: 11,920; sh: 1,785; makefile: 517; xml: 64; perl: 31
file content (280 lines) | stat: -rw-r--r-- 7,137 bytes parent folder | download | duplicates (2)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Sonic Visualiser
    An audio file viewer and annotation editor.
    Centre for Digital Music, Queen Mary, University of London.
    This file copyright 2006 Chris Cannam.
    
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
*/

#include "TempDirectory.h"
#include "ResourceFinder.h"
#include "system/System.h"
#include "Exceptions.h"

#include <QDir>
#include <QFile>
#include <QMutexLocker>
#include <QSettings>

#include <iostream>
#include <cassert>

#include <time.h>

namespace sv {

TempDirectory *
TempDirectory::m_instance = new TempDirectory;

TempDirectory *
TempDirectory::getInstance()
{
    return m_instance;
}

TempDirectory::TempDirectory() :
    m_tmpdir("")
{
}

TempDirectory::~TempDirectory()
{
    SVDEBUG << "TempDirectory::~TempDirectory" << endl;

    cleanup();
}

void
TempDirectory::cleanup()
{
    cleanupDirectory("");
}

QString
TempDirectory::getContainingPath()
{
    QMutexLocker locker(&m_mutex);

    QSettings settings;
    settings.beginGroup("TempDirectory");
    QString svDirParent = settings.value("create-in", "$HOME").toString();
    settings.endGroup();

    QString svDir = ResourceFinder().getUserResourcePrefix();
    if (svDirParent != "$HOME") {
        //!!! iffy
        svDir.replace(QDir::home().absolutePath(), svDirParent);
    }

    if (!QFileInfo(svDir).exists()) {
        if (!QDir(svDirParent).mkpath(svDir)) {
            throw DirectoryCreationFailed(QString("%1 directory in %2")
                                          .arg(svDir).arg(svDirParent));
        }
    } else if (!QFileInfo(svDir).isDir()) {
        throw DirectoryCreationFailed(QString("%1 is not a directory")
                                      .arg(svDir));
    }

    cleanupAbandonedDirectories(svDir);

    return svDir;
}    

QString
TempDirectory::getPath()
{
    if (m_tmpdir != "") return m_tmpdir;

    return createTempDirectoryIn(getContainingPath());
}

QString
TempDirectory::createTempDirectoryIn(QString dir)
{
    // Entered with mutex held.

    QDir tempDirBase(dir);

    // Generate a temporary directory.  Qt4.1 doesn't seem to be able
    // to do this for us, and mkdtemp is not standard.  This method is
    // based on the way glibc does mkdtemp.

    static QString chars =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    QString suffix;
    int padlen = 6, attempts = 100;
    unsigned int r = (unsigned int)(time(nullptr) ^ getpid());

    for (int i = 0; i < padlen; ++i) {
        suffix += "X";
    }
    
    for (int j = 0; j < attempts; ++j) {

        unsigned int v = r;
        
        for (int i = 0; i < padlen; ++i) {
            suffix[i] = chars[v % 62];
            v /= 62;
        }

        QString candidate = QString("sv_%1").arg(suffix);

        if (tempDirBase.mkpath(candidate)) {
            m_tmpdir = tempDirBase.filePath(candidate);
            break;
        }

        r = r + 7777;
    }

    if (m_tmpdir == "") {
        throw DirectoryCreationFailed(QString("temporary subdirectory in %1")
                                      .arg(tempDirBase.canonicalPath()));
    }

    QString pidpath = QDir(m_tmpdir).filePath(QString("%1.pid").arg(getpid()));
    QFile pidfile(pidpath);

    if (!pidfile.open(QIODevice::WriteOnly)) {
        throw DirectoryCreationFailed(QString("pid file creation in %1")
                                      .arg(m_tmpdir));
    } else {
        pidfile.close();
    }

    return m_tmpdir;
}

QString
TempDirectory::getSubDirectoryPath(QString subdir)
{
    QString tmpdirpath = getPath();
    
    QMutexLocker locker(&m_mutex);

    QDir tmpdir(tmpdirpath);
    QFileInfo fi(tmpdir.filePath(subdir));

    if (!fi.exists()) {
        if (!tmpdir.mkdir(subdir)) {
            throw DirectoryCreationFailed(fi.filePath());
        } else {
            return fi.filePath();
        }
    } else if (fi.isDir()) {
        return fi.filePath();
    } else {
        throw DirectoryCreationFailed(fi.filePath());
    }
}

void
TempDirectory::cleanupDirectory(QString tmpdir)
{
    bool isRoot = false;

    if (tmpdir == "") {

        m_mutex.lock();

        isRoot = true;
        tmpdir = m_tmpdir;

        if (tmpdir == "") {
            m_mutex.unlock();
            return;
        }
    }

    QDir dir(tmpdir);
    dir.setFilter(QDir::Dirs | QDir::Files);

    for (unsigned int i = 0; i < dir.count(); ++i) {

        if (dir[i] == "." || dir[i] == "..") continue;
        QFileInfo fi(dir.filePath(dir[i]));

        if (fi.isDir()) {
            cleanupDirectory(fi.absoluteFilePath());
        } else {
            if (!QFile(fi.absoluteFilePath()).remove()) {
                SVCERR << "WARNING: TempDirectory::cleanup: "
                          << "Failed to unlink file \""
                          << fi.absoluteFilePath() << "\""
                          << endl;
            }
        }
    }

    QString dirname = dir.dirName();
    if (dirname != "") {
        if (!dir.cdUp()) {
            SVCERR << "WARNING: TempDirectory::cleanup: "
                      << "Failed to cd to parent directory of "
                      << tmpdir << endl;
            return;
        }
        if (!dir.rmdir(dirname)) {
            SVCERR << "WARNING: TempDirectory::cleanup: "
                      << "Failed to remove directory "
                      << dirname << endl;
        } 
    }

    if (isRoot) {
        m_tmpdir = "";
        m_mutex.unlock();
    }
}

void
TempDirectory::cleanupAbandonedDirectories(QString svDir)
{
    QDir dir(svDir, "sv_*", QDir::Name, QDir::Dirs);

    for (unsigned int i = 0; i < dir.count(); ++i) {
        
        QString dirpath = dir.filePath(dir[i]);

        QDir subdir(dirpath, "*.pid", QDir::Name, QDir::Files);

        if (subdir.count() == 0) {
            SVCERR << "INFO: Found temporary directory with no .pid file in it!\n(directory=\""
                      << dirpath << "\").  Removing it..." << endl;
            cleanupDirectory(dirpath);
            SVCERR << "...done." << endl;
            continue;
        }

        for (unsigned int j = 0; j < subdir.count(); ++j) {

            bool ok = false;
            int pid = QFileInfo(subdir[j]).baseName().toInt(&ok);
            if (!ok) continue;

            if (GetProcessStatus(pid) == ProcessNotRunning) {
                SVCERR << "INFO: Found abandoned temporary directory from "
                          << "a previous, defunct process\n(pid=" << pid
                          << ", directory=\""
                          << dirpath
                          << "\").  Removing it..." << endl;
                cleanupDirectory(dirpath);
                SVCERR << "...done." << endl;
                break;
            }
        }
    }
}

} // end namespace sv