libarchivehandler.cpp 24.2 KB
Newer Older
1
2
/*
 * Copyright (c) 2007 Henrique Pinto <henrique.pinto@kdemail.net>
3
 * Copyright (c) 2008-2009 Harald Hvaal <haraldhv@stud.ntnu.no>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "libarchivehandler.h"
28
#include "kerfuffle/kerfuffle_export.h"
29
#include "kerfuffle/queries.h"
30
31
32
33

#include <archive.h>
#include <archive_entry.h>

34
#include <KDebug>
35
#include <KLocale>
36
#include <kde_file.h>
37

38
#include <QDateTime>
39
#include <QDir>
40
41
#include <QDirIterator>
#include <QFile>
42
43
44
#include <QList>
#include <QStringList>

45
46
LibArchiveInterface::LibArchiveInterface(QObject *parent, const QVariantList & args)
        : ReadWriteArchiveInterface(parent, args),
47
48
49
        m_cachedArchiveEntryCount(0),
        m_emitNoEntries(false),
        m_extractedFilesSize(0)
50
51
52
53
54
55
56
57
58
{
}

LibArchiveInterface::~LibArchiveInterface()
{
}

bool LibArchiveInterface::list()
{
59
    kDebug();
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
    struct archive *arch;
    struct archive_entry *aentry;
    int result;

    arch = archive_read_new();
    if (!arch)
        return false;

    result = archive_read_support_compression_all(arch);
    if (result != ARCHIVE_OK) return false;

    result = archive_read_support_format_all(arch);
    if (result != ARCHIVE_OK) return false;

    result = archive_read_open_filename(arch, QFile::encodeName(filename()), 10240);

    if (result != ARCHIVE_OK) {
        error(i18n("Could not open the file '%1', libarchive cannot handle it.", filename()), QString());
        return false;
    }

    m_cachedArchiveEntryCount = 0;
    m_extractedFilesSize = 0;

    while ((result = archive_read_next_header(arch, &aentry)) == ARCHIVE_OK) {
        if (!m_emitNoEntries) emitEntryFromArchiveEntry(aentry);
        m_extractedFilesSize += (qlonglong) archive_entry_size(aentry);

        m_cachedArchiveEntryCount++;
        archive_read_data_skip(arch);
    }

    if (result != ARCHIVE_EOF) {
        error(i18n("The archive reading failed with message: %1", archive_error_string(arch)));
        return false;
    }
96

97
#if (ARCHIVE_API_VERSION>1)
98
    return archive_read_finish(arch) == ARCHIVE_OK;
99
#else
100
    return true;
101
#endif
102
103
}

104
bool LibArchiveInterface::copyFiles(const QList<QVariant> & files, const QString & destinationDirectory, ExtractionOptions options)
105
{
106
    kDebug() << "Changing current directory to " << destinationDirectory;
107
108
109
110
111
112
113
114
115
116
117
118
119
    QDir::setCurrent(destinationDirectory);

    const bool extractAll = files.isEmpty();
    const bool preservePaths = options.value("PreservePaths").toBool();

    //TODO: don't leak these if the extraction fails with an error in the
    //middle
    struct archive *arch, *writer;
    struct archive_entry *entry;

    QString rootNode;
    if (options.contains("RootNode")) {
        rootNode = options.value("RootNode").toString();
120
        kDebug() << "Set root node " << rootNode;
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
    }

    arch = archive_read_new();
    if (!arch) {
        return false;
    }

    writer = archive_write_disk_new();
    archive_write_disk_set_options(writer, extractionFlags());

    archive_read_support_compression_all(arch);
    archive_read_support_format_all(arch);
    int res = archive_read_open_filename(arch, QFile::encodeName(filename()), 10240);

    if (res != ARCHIVE_OK) {
        error(i18n("Unable to open the file '%1', libarchive cannot handle it.", filename())) ;
        return false;
    }

    int entryNr = 0, totalCount = 0;
    if (extractAll) {
        if (!m_cachedArchiveEntryCount) {
            progress(0);
            //TODO: once information progress has been implemented, send
            //feedback here that the archive is being read
146
            kDebug() << "For getting progress information, the archive will be listed once";
147
148
149
150
151
152
153
154
155
156
157
158
159
            m_emitNoEntries = true;
            list();
            m_emitNoEntries = false;
        }
        totalCount = m_cachedArchiveEntryCount;
    } else
        totalCount = files.size();
    m_currentExtractedFilesSize = 0;

    bool overwriteAll = false; // Whether to overwrite all files
    bool skipAll = false; // Whether to skip all files

    while (archive_read_next_header(arch, &entry) == ARCHIVE_OK) {
160
        //retry with renamed entry, fire an overwrite query again if the new entry also exists
161
162
163
    retry:
        const bool entryIsDir = S_ISDIR(archive_entry_mode(entry));

Harald Hvaal's avatar
Harald Hvaal committed
164
        //we skip directories if not preserving paths
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        if (!preservePaths && entryIsDir) {
            archive_read_data_skip(arch);
            continue;
        }

        //entryName is the name inside the archive, full path
        QString entryName = QDir::fromNativeSeparators(QFile::decodeName(archive_entry_pathname(entry)));

        if (entryName.startsWith('/')) {
            //for now we just can't handle absolute filenames in a tar archive.
            //TODO: find out what to do here!!
            error(i18n("This archive contains archive entries with absolute paths, which are not yet supported by ark."));
            return false;
        }

        if (files.contains(entryName) || extractAll) {
            // entryFI is the fileinfo pointing to where the file will be
            // written from the archive
            QFileInfo entryFI(entryName);
184
            //kDebug() << "setting path to " << archive_entry_pathname( entry );
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202

            QString fileWithoutPath = entryFI.fileName();

            //if we DON'T preserve paths, we cut the path and set the entryFI
            //fileinfo to the one without the path
            if (!preservePaths) {
                //empty filenames (ie dirs) should have been skipped already,
                //so asserting
                Q_ASSERT(!fileWithoutPath.isEmpty());

                archive_entry_copy_pathname(entry, QFile::encodeName(fileWithoutPath).constData());
                entryFI = QFileInfo(fileWithoutPath);

                //OR, if the commonBase has been set, then we remove this
                //common base from the filename
            } else if (!rootNode.isEmpty()) {
                QString truncatedFilename;
                truncatedFilename = entryName.remove(0, rootNode.size());
203
                kDebug() << "Truncated filename: " << truncatedFilename;
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
                archive_entry_copy_pathname(entry, QFile::encodeName(truncatedFilename).constData());

                entryFI = QFileInfo(truncatedFilename);
            }

            //now check if the file about to be written already exists
            if (!entryIsDir && entryFI.exists()) {
                if (skipAll) {
                    archive_read_data_skip(arch);
                    archive_entry_clear(entry);
                    continue;
                } else if (!overwriteAll && !skipAll) {
                    Kerfuffle::OverwriteQuery query(entryName);
                    userQuery(&query);
                    query.waitForResponse();

                    if (query.responseCancelled()) {
                        archive_read_data_skip(arch);
                        archive_entry_clear(entry);
                        break;
                    } else if (query.responseSkip()) {
                        archive_read_data_skip(arch);
                        archive_entry_clear(entry);
                        continue;
                    } else if (query.responseAutoSkip()) {
                        archive_read_data_skip(arch);
                        archive_entry_clear(entry);
                        skipAll = true;
                        continue;
                    } else if (query.responseRename()) {
                        QString newName = query.newFilename();
                        archive_entry_copy_pathname(entry, QFile::encodeName(newName).constData());
                        goto retry;
                    } else if (query.responseOverwriteAll()) {
                        overwriteAll = true;
                    }
                }
            }

Harald Hvaal's avatar
Harald Hvaal committed
243
244
245
246
247
248
249
250
251
252
253
254
            //if there is an already existing directory:
            if (entryIsDir && entryFI.exists()) {
                if (entryFI.isWritable()) {
                    kDebug(1601) << "Warning, existing, but writable dir";
                } else {
                    kDebug(1601) << "Warning, existing, but non-writable dir. skipping";
                    archive_entry_clear(entry);
                    archive_read_data_skip(arch);
                    continue;
                }
            }

255
            int header_response;
256
            kDebug() << "Writing " << fileWithoutPath << " to " << archive_entry_pathname(entry);
257
258
259
260
            if ((header_response = archive_write_header(writer, entry)) == ARCHIVE_OK)
                //if the whole archive is extracted and the total filesize is
                //available, we use partial progress
                copyData(arch, writer, (extractAll && m_extractedFilesSize));
Harald Hvaal's avatar
Harald Hvaal committed
261
262
263
            else if (header_response == ARCHIVE_WARN) {
                kDebug() << "Warning while writing " << entryName;
            } else {
264
                kDebug() << "Writing header failed with error code " << header_response
Harald Hvaal's avatar
Harald Hvaal committed
265
                << "While attempting to write " << entryName;
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
            }

            //if we only partially extract the archive and the number of
            //archive entries is available we use a simple progress based on
            //number of items extracted
            if (!extractAll && m_cachedArchiveEntryCount) {
                ++entryNr;
                progress(float(entryNr) / totalCount);
            }
            archive_entry_clear(entry);
        } else {
            archive_read_data_skip(arch);
        }
    }

    archive_write_finish(writer);
Harald Hvaal's avatar
Harald Hvaal committed
282

283
#if (ARCHIVE_API_VERSION>1)
284
    return archive_read_finish(arch) == ARCHIVE_OK;
285
#else
286
    return true;
287
#endif
288
289
}

290
bool LibArchiveInterface::addFiles(const QStringList & files, const CompressionOptions& options)
291
{
292
293
294
295
296
297
298
299
    struct archive *arch_reader = NULL, *arch_writer = NULL;
    struct archive_entry *entry;
    int header_response;
    int ret;
    const bool creatingNewFile = !QFileInfo(filename()).exists();

    QString tempFilename = filename() + ".arkWriting";

300
    kDebug() << "Current path " << QDir::currentPath();
301
302
303

    QString globalWorkdir = options.value("GlobalWorkDir").toString();
    if (!globalWorkdir.isEmpty()) {
304
        kDebug() << "GlobalWorkDir is set, changing dir to " << globalWorkdir;
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        QDir::setCurrent(globalWorkdir);
    }

    m_writtenFiles.clear();

    if (!creatingNewFile) {
        //*********initialize the reader
        arch_reader = archive_read_new();
        if (!arch_reader) {
            error(i18n("The archive reader could not be initialized."));
            return false;
        }

        archive_read_support_compression_all(arch_reader);
        archive_read_support_format_all(arch_reader);
        ret = archive_read_open_filename(arch_reader, QFile::encodeName(filename()), 10240);
        if (ret != ARCHIVE_OK) {
            error(i18n("The source file could not be read."));
            return false;
        }
    }

    //*********initialize the writer
    arch_writer = archive_write_new();
    if (!arch_writer) {
        error(i18n("The archive writer could not be initialized."));
        return false;
    }

    //pax_restricted is the libarchive default, let's go with that.
    archive_write_set_format_pax_restricted(arch_writer);

    if (creatingNewFile) {
        if (filename().right(2).toUpper() == "GZ") {
339
            kDebug() << "Detected gzip compression for new file";
340
341
            ret = archive_write_set_compression_gzip(arch_writer);
        } else if (filename().right(3).toUpper() == "BZ2") {
342
            kDebug() << "Detected bzip2 compression for new file";
343
            ret = archive_write_set_compression_bzip2(arch_writer);
344
        } else if (filename().right(3).toUpper() == "TAR") {
345
            kDebug() << "Detected no compression for new file (pure tar)";
346
            ret = archive_write_set_compression_none(arch_writer);
347
        } else {
348
            kDebug() << "Falling back to gzip";
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
            ret = archive_write_set_compression_gzip(arch_writer);
        }

        if (ret != ARCHIVE_OK) {
            error(i18n("Setting compression failed with the error '%1'", QString(archive_error_string(arch_writer))));
            return false;
        }

        if (ret != ARCHIVE_OK) {
            error(i18n("Setting format failed with the error '%1'", QString(archive_error_string(arch_writer))));
            return false;
        }
    } else {
        switch (archive_compression(arch_reader)) {
        case ARCHIVE_COMPRESSION_GZIP:
            ret = archive_write_set_compression_gzip(arch_writer);
            break;
        case ARCHIVE_COMPRESSION_BZIP2:
            ret = archive_write_set_compression_bzip2(arch_writer);
            break;
        case ARCHIVE_COMPRESSION_NONE:
            ret = archive_write_set_compression_none(arch_writer);
            break;
        default:
            error(i18n("The compression type '%1' is not supported by Ark.", QString(archive_compression_name(arch_reader))));
            return false;
        }
        if (ret != ARCHIVE_OK) {
            error(i18n("Setting compression failed with the error '%1'", QString(archive_error_string(arch_writer))));
            return false;
        }
    }

    ret = archive_write_open_filename(arch_writer, QFile::encodeName(tempFilename));
    if (ret != ARCHIVE_OK) {
        error(i18n("Opening the archive for writing failed with error message '%1'", QString(archive_error_string(arch_writer))));
        return false;
    }

    entry = archive_entry_new();

    //**************** first write the new files
    foreach(const QString& selectedFile, files) {
        bool success;

        success = writeFile(selectedFile, arch_writer, entry);

        if (!success)
            return false;

        if (QFileInfo(selectedFile).isDir()) {
            QDirIterator it(selectedFile, QDir::AllEntries | QDir::Readable | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

            while (it.hasNext()) {
                QString path = it.next();
                if (it.fileName() == ".." || it.fileName() == ".") continue;

                success = writeFile(path +
                                    (it.fileInfo().isDir() ? "/" : "")
                                    , arch_writer, entry);

                if (!success)
                    return false;
            }
        }
    }

    //and if we have old elements...
    if (!creatingNewFile) {
        //********** copy old elements from previous archive to new archive
        while (archive_read_next_header(arch_reader, &entry) == ARCHIVE_OK) {
            if (m_writtenFiles.contains(QFile::decodeName(archive_entry_pathname(entry)))) {
                archive_read_data_skip(arch_reader);
422
                kDebug() << "Entry already existing, will be refresh: ===> " << archive_entry_pathname(entry);
423
424
425
                continue;
            }

426
            //kDebug() << "Writing entry " << fn;
427
428
429
430
431
            if ((header_response = archive_write_header(arch_writer, entry)) == ARCHIVE_OK)
                //if the whole archive is extracted and the total filesize is
                //available, we use partial progress
                copyData(arch_reader, arch_writer, false);
            else {
432
                kDebug() << "Writing header failed with error code " << header_response;
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
                return false;
            }

            archive_entry_clear(entry);
        }
    }

    ret = archive_write_finish(arch_writer);

    if (!creatingNewFile) {
        archive_read_finish(arch_reader);

        //everything seems OK, so we remove the source file and replace it with
        //the new one.
        //TODO: do some extra checks to see if this is really OK
        QFile::remove(filename());
    }

    QFile::rename(tempFilename, filename());

    return true;
454
455
}

456
bool LibArchiveInterface::deleteFiles(const QList<QVariant> & files)
457
{
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    struct archive *arch_reader = NULL, *arch_writer = NULL;
    struct archive_entry *entry;
    int header_response;
    int ret;

    QString tempFilename = filename() + ".arkWriting";

    arch_reader = archive_read_new();
    if (!arch_reader) {
        error(i18n("The archive reader could not be initialized."));
        return false;
    }

    archive_read_support_compression_all(arch_reader);
    archive_read_support_format_all(arch_reader);
    ret = archive_read_open_filename(arch_reader, QFile::encodeName(filename()), 10240);
    if (ret != ARCHIVE_OK) {
        error(i18n("The source file could not be read."));
        return false;
    }

    //*********initialize the writer
    arch_writer = archive_write_new();
    if (!arch_writer) {
        error(i18n("The archive writer could not be initialized."));
        return false;
    }

    //pax_restricted is the libarchive default, let's go with that.
    archive_write_set_format_pax_restricted(arch_writer);

    switch (archive_compression(arch_reader)) {
    case ARCHIVE_COMPRESSION_GZIP:
        ret = archive_write_set_compression_gzip(arch_writer);
        break;
    case ARCHIVE_COMPRESSION_BZIP2:
        ret = archive_write_set_compression_bzip2(arch_writer);
        break;
    case ARCHIVE_COMPRESSION_NONE:
        ret = archive_write_set_compression_none(arch_writer);
        break;
    default:
        error(i18n("The compression type '%1' is not supported by Ark.", QString(archive_compression_name(arch_reader))));
        return false;
    }

    if (ret != ARCHIVE_OK) {
        error(i18n("Setting compression failed with the error '%1'", QString(archive_error_string(arch_writer))));
        return false;
    }

    ret = archive_write_open_filename(arch_writer, QFile::encodeName(tempFilename));
    if (ret != ARCHIVE_OK) {
        error(i18n("Opening the archive for writing failed with error message '%1'", QString(archive_error_string(arch_writer))));
        return false;
    }

    entry = archive_entry_new();

    //********** copy old elements from previous archive to new archive
    while (archive_read_next_header(arch_reader, &entry) == ARCHIVE_OK) {
        if (files.contains(QFile::decodeName(archive_entry_pathname(entry)))) {
            archive_read_data_skip(arch_reader);
521
            kDebug() << "Entry to be deleted, skipping" << archive_entry_pathname(entry);
522
523
524
525
            entryRemoved(QFile::decodeName(archive_entry_pathname(entry)));
            continue;
        }

526
        //kDebug() << "Writing entry " << fn;
527
528
529
530
531
532
        if ((header_response = archive_write_header(arch_writer, entry)) == ARCHIVE_OK)

            //if the whole archive is extracted and the total filesize is
            //available, we use partial progress
            copyData(arch_reader, arch_writer, false);
        else {
533
            kDebug() << "Writing header failed with error code " << header_response;
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
            return false;
        }

        archive_entry_clear(entry);
    }

    ret = archive_write_finish(arch_writer);

    archive_read_finish(arch_reader);

    //everything seems OK, so we remove the source file and replace it with
    //the new one.
    //TODO: do some extra checks to see if this is really OK
    QFile::remove(filename());
    QFile::rename(tempFilename, filename());

    return true;
551
552
}

553
void LibArchiveInterface::emitEntryFromArchiveEntry(struct archive_entry *aentry)
554
{
555
    ArchiveEntry e;
556
#ifdef _MSC_VER
557
    e[ FileName ] = QDir::fromNativeSeparators(QString::fromUtf16((ushort*)archive_entry_pathname_w(aentry)));
558
#else
559
    e[ FileName ] = QDir::fromNativeSeparators(QString::fromWCharArray(archive_entry_pathname_w(aentry)));
560
#endif
561
    e[ InternalID ] = e[ FileName ];
562

563
564
    QString owner = QString(archive_entry_uname(aentry));
    if (!owner.isEmpty()) e[ Owner ] = owner;
565

566
567
    QString group = QString(archive_entry_gname(aentry));
    if (!group.isEmpty()) e[ Group ] = group;
568

569
570
571
572
573
574
    e[ Size ] = (qlonglong) archive_entry_size(aentry);
    e[ IsDirectory ] = S_ISDIR(archive_entry_mode(aentry));     // see stat(2)
    if (archive_entry_symlink(aentry)) {
        e[ Link ] = archive_entry_symlink(aentry);
    }
    e[ Timestamp ] = QDateTime::fromTime_t(archive_entry_mtime(aentry));
575

576
    entry(e);
577
578
579
580
}

int LibArchiveInterface::extractionFlags() const
{
581
582
    int result = ARCHIVE_EXTRACT_TIME;
    result |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
583

584
585
586
587
588
    // TODO: Don't use arksettings here
    /*if ( ArkSettings::preservePerms() )
    {
        result &= ARCHIVE_EXTRACT_PERM;
    }
589

590
591
592
593
    if ( !ArkSettings::extractOverwrite() )
    {
        result &= ARCHIVE_EXTRACT_NO_OVERWRITE;
    }*/
594

595
    return result;
596
597
}

598
void LibArchiveInterface::copyData(const QString& filename, struct archive *dest, bool partialprogress)
599
{
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
    char buff[ARCHIVE_DEFAULT_BYTES_PER_BLOCK];
    ssize_t readBytes;
    QFile file(filename);

    if (!file.open(QIODevice::ReadOnly))
        return;

    readBytes = file.read(buff, sizeof(buff));
    while (readBytes > 0) {
        /* int writeBytes = */
        archive_write_data(dest, buff, readBytes);
        if (archive_errno(dest) != ARCHIVE_OK) {
            kDebug() << "Error while writing..." << archive_error_string(dest) << "(error nb =" << archive_errno(dest) << ')';
            return;
        }

        if (partialprogress) {
            m_currentExtractedFilesSize += readBytes;
            progress(float(m_currentExtractedFilesSize) / m_extractedFilesSize);
        }

        readBytes = file.read(buff, sizeof(buff));
    }

    file.close();
625
626
}

627
void LibArchiveInterface::copyData(struct archive *source, struct archive *dest, bool partialprogress)
628
{
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
    char buff[ARCHIVE_DEFAULT_BYTES_PER_BLOCK];
    ssize_t readBytes;

    readBytes = archive_read_data(source, buff, sizeof(buff));
    while (readBytes > 0) {
        /* int writeBytes = */
        archive_write_data(dest, buff, readBytes);
        if (archive_errno(dest) != ARCHIVE_OK) {
            kDebug() << "Error while extracting..." << archive_error_string(dest) << "(error nb =" << archive_errno(dest) << ')';
            return;
        }

        if (partialprogress) {
            m_currentExtractedFilesSize += readBytes;
            progress(float(m_currentExtractedFilesSize) / m_extractedFilesSize);
        }

        readBytes = archive_read_data(source, buff, sizeof(buff));
    }
648
649
}

650
bool LibArchiveInterface::writeFile(const QString& fileName, struct archive* arch_writer, struct archive_entry* entry)
651
{
652
653
    KDE_struct_stat st;
    int header_response;
654

Laurent Montel's avatar
Laurent Montel committed
655
    const bool trailingSlash = fileName.endsWith('/');
656
    QString relativeName = QDir::current().relativeFilePath(fileName) + (trailingSlash ? "/" : "");
657

658
659
660
    KDE_stat(QFile::encodeName(relativeName).constData(), &st);
    archive_entry_copy_stat(entry, &st);
    archive_entry_copy_pathname(entry, QFile::encodeName(relativeName).constData());
661

662
    kDebug() << "Writing new entry " << archive_entry_pathname(entry);
663
664
665
666
667
    if ((header_response = archive_write_header(arch_writer, entry)) == ARCHIVE_OK)
        //if the whole archive is extracted and the total filesize is
        //available, we use partial progress
        copyData(fileName, arch_writer, false);
    else {
668
        kDebug() << "Writing header failed with error code " << header_response;
669
670
671
        kDebug() << "Error while writing..." << archive_error_string(arch_writer) << "(error nb =" << archive_errno(arch_writer) << ')';
        return false;
    }
672

673
    m_writtenFiles.push_back(relativeName);
674

675
676
    emitEntryFromArchiveEntry(entry);
    archive_entry_clear(entry);
677

678
    return true;
679
680
}

681
KERFUFFLE_EXPORT_PLUGIN(LibArchiveInterface)
682
683

#include "libarchivehandler.moc"