File: SafeFileSaver.cpp

package info (click to toggle)
amarok 3.3.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 112,168 kB
  • sloc: cpp: 195,056; xml: 4,322; ansic: 2,634; javascript: 673; ruby: 528; python: 507; sh: 252; makefile: 12
file content (257 lines) | stat: -rw-r--r-- 7,534 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
/*
 *  Copyright (c) 2008-2009 Jeff Mitchell <mitchell@kde.org>
 *
 *  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.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "SafeFileSaver.h"

#include <QtDebug>
#include <QCryptographicHash>
#include <QFile>
#include <QFileInfo>
#include <QRandomGenerator>
#include <QString>

#ifdef Q_OS_WINDOWS
#include <process.h>
#else
#include <unistd.h>
#include <sys/types.h>
#endif

SafeFileSaver::SafeFileSaver( const QString &origPath )
    : m_origPath( origPath )
    , m_tempSavePath()
    , m_origRenamedSavePath()
    , m_cleanupNeeded( false )
    , m_verbose( false )
    , m_prefix( QStringLiteral("safefilesaver") )
{
}

SafeFileSaver::~SafeFileSaver()
{
    if( m_cleanupNeeded )
        cleanupSave();
}

QString
SafeFileSaver::prepareToSave()
{
    if( m_verbose )
        qDebug() << "prepareToSave start";
    m_cleanupNeeded = true;
    QCryptographicHash md5sum( QCryptographicHash::Md5 ); 

    QString pid;
#ifdef Q_OS_WINDOWS
    pid.setNum( _getpid() );
#else
    pid.setNum( getpid() );
#endif

    int length = 8;
    //The following snippet of code is copied from kdelibs, and is copyright Matthias Kalle Dalheimer, Charles Samuels, Joseph Wenninger, and maybe more
    QString str; str.resize( length );
    int i = 0;
    while( length-- )
    {
        int r = QRandomGenerator::global()->generate() % 62;
        r+=48;
        if( r > 57 ) r+=7;
        if( r > 90 ) r+=6;
        str[i++] = QLatin1Char( r );
    }

    QString randomString = str;

    m_tempSavePath = m_origPath + QLatin1Char('.') + m_prefix + QStringLiteral("temp.pid-") + pid + QStringLiteral(".random-") + randomString + QLatin1Char('.') + QFileInfo( m_origPath ).suffix();
    m_origRenamedSavePath = m_origPath + QLatin1Char('.') + m_prefix + QStringLiteral("original.pid-") + pid + QStringLiteral(".random-") + randomString + QLatin1Char('.') + QFileInfo( m_origPath ).suffix();


    if( m_verbose )
        qDebug() << "Copying original file " << m_origPath << " to copy at " << m_tempSavePath << " and caluclating MD5";

    if( !QFile::copy( m_origPath, m_tempSavePath ) )
    {
        if( m_verbose )
            qDebug() << "Could not copy the file.  Check that you have sufficient permissions/disk space "
                   "and that the destination path does not already exist!";
        return QString();
    }

    QFile tempFile( m_tempSavePath );
    if( !tempFile.open( QIODevice::ReadOnly | QIODevice::Unbuffered ) )
    {
        if( m_verbose )
            qDebug() << "Could not open temp file for MD5 calculation!";
        return QString();
    }

    md5sum.addData( tempFile.readLine() );
    m_tempSaveDigest = QLatin1String( md5sum.result().toHex() );

    tempFile.close();

    //By this point, we have the following:
    //The original file is copied at path m_tempSavePath
    //We have generated what will be the filename to rename the original to in m_origRenamedSavePath
    //We have successfully copied the original file to the temp location
    //We've calculated the md5sum of the original file

    if( m_verbose )
        qDebug() << "MD5 sum of temp file: " << m_tempSaveDigest;

    //Now, we have a MD5 sum of the original file at the time of copying saved in m_tempSaveDigest

    return m_tempSavePath;
}

bool
SafeFileSaver::doSave()
{
    if( m_verbose )
        qDebug() << "doSave start";
    //TODO: much commenting needed.  For now this pretty much follows algorithm laid out in bug 131353,
    //but isn't useable since I need to find a good way to switch the file path with taglib, or a good way
    //to get all the metadata copied over.

    m_cleanupNeeded = true;

    QCryptographicHash md5sum( QCryptographicHash::Md5 ); 

    QString origRenamedDigest;

    if( m_tempSavePath.isEmpty() || m_tempSaveDigest.isEmpty() || m_origRenamedSavePath.isEmpty() )
    {
        if( m_verbose)
            qDebug() << "You must run prepareToSave() and it must return successfully before calling doSave()!";
        return false;
    }

    if( m_verbose )
        qDebug() << "Renaming original file to temporary name " << m_origRenamedSavePath;

    if( !QFile::rename( m_origPath, m_origRenamedSavePath ) )
    {
        if( m_verbose )
            qDebug() << "Could not move original!";
        failRemoveCopy( false );
        return false;
    }

    if( m_verbose )
        qDebug() << "Calculating MD5 of " << m_origRenamedSavePath;

    QFile origRenamedFile( m_origRenamedSavePath );
    if( !origRenamedFile.open( QIODevice::ReadOnly | QIODevice::Unbuffered ) )
    {
        if( m_verbose )
            qDebug() << "Could not open temporary file!";
        failRemoveCopy( true );
        return false;
    }

    md5sum.addData( origRenamedFile.readLine() );
    origRenamedDigest = QLatin1String( md5sum.result().toHex() );
    origRenamedFile.close();

    if( m_verbose )
        qDebug() << "md5sum of original renamed file: " << origRenamedDigest;

    if( origRenamedDigest != m_tempSaveDigest )
    {
        if( m_verbose )
            qDebug() << "Original checksum did not match current checksum!";
        failRemoveCopy( true );
        return false;
    }

    if( m_verbose )
        qDebug() << "Renaming temp file to original's filename";

    if( !QFile::rename( m_tempSavePath, m_origPath ) )
    {
        if( m_verbose )
            qDebug() << "Could not rename new file to original!";
        failRemoveCopy( true );
        return false;
    }

    if( m_verbose )
        qDebug() << "Deleting original";

    if( !QFile::remove( m_origRenamedSavePath ) )
    {
        if( m_verbose )
            qDebug() << "Could not delete the original file!";
        return false;
    }

    if( m_verbose )
        qDebug() << "Save done, returning true!";

    return true;
}

void
SafeFileSaver::failRemoveCopy( bool revert )
{
    if( m_verbose )
        qDebug() << "failRemoveCopy start";
    if( !QFile::remove( m_tempSavePath ) )
    {
        if( m_verbose )
            qDebug() << "Could not delete the temporary file!";
    }

    if( !revert )
        return;

    if( m_verbose )
        qDebug() << "Reverting original file to original filename!";
    if( !QFile::rename( m_origRenamedSavePath, m_origPath ) )
    {
        if( m_verbose )
            qDebug() << "Could not revert file to original filename!";
    }
}

bool
SafeFileSaver::cleanupSave()
{
    if( m_verbose )
        qDebug() << "cleanupSave start";
    bool dirty = false;

    if( !m_tempSavePath.isEmpty() && QFile::exists( m_tempSavePath ) )
    {
        if( !QFile::remove( m_tempSavePath ) )
        {
            dirty = true;
            if( m_verbose )
                qDebug() << "Could not delete the temporary file!";
        }
    }

    m_tempSavePath.clear();
    m_origRenamedSavePath.clear();
    m_tempSaveDigest.clear();

    m_cleanupNeeded = false;
    return !dirty;
}