Coverage Report

Created: 2026-05-16 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ogre/OgreMain/src/OgreZip.cpp
Line
Count
Source
1
/*
2
-----------------------------------------------------------------------------
3
This source file is part of OGRE
4
(Object-oriented Graphics Rendering Engine)
5
For the latest info, see http://www.ogre3d.org/
6
7
Copyright (c) 2000-2014 Torus Knot Software Ltd
8
9
Permission is hereby granted, free of charge, to any person obtaining a copy
10
of this software and associated documentation files (the "Software"), to deal
11
in the Software without restriction, including without limitation the rights
12
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
copies of the Software, and to permit persons to whom the Software is
14
furnished to do so, subject to the following conditions:
15
16
The above copyright notice and this permission notice shall be included in
17
all copies or substantial portions of the Software.
18
19
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
THE SOFTWARE.
26
-----------------------------------------------------------------------------
27
*/
28
#include "OgreStableHeaders.h"
29
30
#if OGRE_NO_ZIP_ARCHIVE == 0
31
#include <zip.h>
32
33
namespace Ogre {
34
namespace {
35
    class ZipArchive : public Archive
36
    {
37
    protected:
38
        /// Handle to root zip file
39
        zip_t* mZipFile;
40
        MemoryDataStreamPtr mBuffer;
41
        /// File list (since zziplib seems to only allow scanning of dir tree once)
42
        FileInfoList mFileList;
43
        OGRE_AUTO_MUTEX;
44
    public:
45
        ZipArchive(const String& name, const String& archType, const uint8* externBuf = 0, size_t externBufSz = 0);
46
        ~ZipArchive();
47
        /// @copydoc Archive::isCaseSensitive
48
0
        bool isCaseSensitive(void) const override { return OGRE_RESOURCEMANAGER_STRICT != 0; }
49
50
        /// @copydoc Archive::load
51
        void load() override;
52
        /// @copydoc Archive::unload
53
        void unload() final override;
54
55
        /// @copydoc Archive::open
56
        DataStreamPtr open(const String& filename, bool readOnly = true) const override;
57
58
        /// @copydoc Archive::create
59
        DataStreamPtr create(const String& filename) override;
60
61
        /// @copydoc Archive::remove
62
        void remove(const String& filename) override;
63
64
        /// @copydoc Archive::list
65
        StringVectorPtr list(bool recursive = true, bool dirs = false) const override;
66
67
        /// @copydoc Archive::listFileInfo
68
        FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const override;
69
70
        /// @copydoc Archive::find
71
        StringVectorPtr find(const String& pattern, bool recursive = true,
72
            bool dirs = false) const override;
73
74
        /// @copydoc Archive::findFileInfo
75
        FileInfoListPtr findFileInfo(const String& pattern, bool recursive = true,
76
            bool dirs = false) const override;
77
78
        /// @copydoc Archive::exists
79
        bool exists(const String& filename) const override;
80
81
        /// @copydoc Archive::getModifiedTime
82
        time_t getModifiedTime(const String& filename) const override;
83
    };
84
}
85
    //-----------------------------------------------------------------------
86
    ZipArchive::ZipArchive(const String& name, const String& archType, const uint8* externBuf, size_t externBufSz)
87
0
        : Archive(name, archType), mZipFile(0)
88
0
    {
89
0
        if(externBuf)
90
0
            mBuffer.reset(new MemoryDataStream(const_cast<uint8*>(externBuf), externBufSz));
91
0
    }
92
    //-----------------------------------------------------------------------
93
    ZipArchive::~ZipArchive()
94
0
    {
95
0
        unload();
96
0
    }
97
    //-----------------------------------------------------------------------
98
    void ZipArchive::load()
99
0
    {
100
0
        OGRE_LOCK_AUTO_MUTEX;
101
0
        if (!mZipFile)
102
0
        {
103
0
            if(!mBuffer)
104
0
                mBuffer.reset(new MemoryDataStream(_openFileStream(mName, std::ios::binary)));
105
106
0
            mZipFile = zip_stream_open((const char*)mBuffer->getPtr(), mBuffer->size(), 0, 'r');
107
108
            // Cache names
109
0
            int n = zip_entries_total(mZipFile);
110
0
            for (int i = 0; i < n; ++i) {
111
0
                FileInfo info;
112
0
                info.archive = this;
113
114
0
                zip_entry_openbyindex(mZipFile, i);
115
116
0
                info.filename = zip_entry_name(mZipFile);
117
                // Get basename / path
118
0
                StringUtil::splitFilename(info.filename, info.basename, info.path);
119
120
                // Get sizes
121
0
                info.uncompressedSize = zip_entry_size(mZipFile);
122
0
                info.compressedSize = zip_entry_comp_size(mZipFile);
123
124
0
                if (zip_entry_isdir(mZipFile))
125
0
                {
126
0
                    info.filename = info.filename.substr(0, info.filename.length() - 1);
127
0
                    StringUtil::splitFilename(info.filename, info.basename, info.path);
128
                    // Set compressed size to -1 for folders; anyway nobody will check
129
                    // the compressed size of a folder, and if he does, its useless anyway
130
0
                    info.compressedSize = size_t(-1);
131
0
                }
132
#if !OGRE_RESOURCEMANAGER_STRICT
133
                else
134
                {
135
                    info.filename = info.basename;
136
                }
137
#endif
138
0
                zip_entry_close(mZipFile);
139
0
                mFileList.push_back(info);
140
0
            }
141
0
        }
142
0
    }
143
    //-----------------------------------------------------------------------
144
    void ZipArchive::unload()
145
0
    {
146
0
        OGRE_LOCK_AUTO_MUTEX;
147
0
        if (mZipFile)
148
0
        {
149
0
            zip_close(mZipFile);
150
0
            mZipFile = 0;
151
0
            mFileList.clear();
152
0
            mBuffer.reset();
153
0
        }
154
    
155
0
    }
156
    //-----------------------------------------------------------------------
157
    DataStreamPtr ZipArchive::open(const String& filename, bool readOnly) const
158
0
    {
159
        // zip is not threadsafe
160
0
        OGRE_LOCK_AUTO_MUTEX;
161
0
        String lookUpFileName = filename;
162
163
0
#if OGRE_RESOURCEMANAGER_STRICT
164
0
        bool open = zip_entry_opencasesensitive(mZipFile, lookUpFileName.c_str()) == 0;
165
#else
166
        bool open = zip_entry_open(mZipFile, lookUpFileName.c_str()) == 0;
167
        if (!open) // Try if we find the file
168
        {
169
            String basename, path;
170
            StringUtil::splitFilename(lookUpFileName, basename, path);
171
            const FileInfoListPtr fileNfo = findFileInfo(basename, true);
172
            if (fileNfo->size() == 1) // If there are more files with the same do not open anyone
173
            {
174
                Ogre::FileInfo info = fileNfo->at(0);
175
                lookUpFileName = info.path + info.basename;
176
                open = zip_entry_open(mZipFile, lookUpFileName.c_str(), OGRE_RESOURCEMANAGER_STRICT) == 0;
177
            }
178
        }
179
#endif
180
181
0
        if (!open)
182
0
        {
183
0
            OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "could not open "+lookUpFileName);
184
0
        }
185
186
        // Construct & return stream
187
0
        auto ret = std::make_shared<MemoryDataStream>(lookUpFileName, zip_entry_size(mZipFile), true, true);
188
189
0
        if(zip_entry_noallocread(mZipFile, ret->getPtr(), ret->size()) < 0)
190
0
            OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "could not read "+lookUpFileName);
191
0
        zip_entry_close(mZipFile);
192
193
0
        return ret;
194
0
    }
195
    //---------------------------------------------------------------------
196
    DataStreamPtr ZipArchive::create(const String& filename)
197
0
    {
198
0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Modification of zipped archives is not implemented");
199
0
    }
200
    //---------------------------------------------------------------------
201
    void ZipArchive::remove(const String& filename)
202
0
    {
203
0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Modification of zipped archives is not implemented");
204
0
    }
205
    //-----------------------------------------------------------------------
206
    StringVectorPtr ZipArchive::list(bool recursive, bool dirs) const
207
0
    {
208
0
        OGRE_LOCK_AUTO_MUTEX;
209
0
        auto ret = std::make_shared<StringVector>();
210
211
0
        for (auto& f : mFileList)
212
0
            if ((dirs == (f.compressedSize == size_t (-1))) &&
213
0
                (recursive || f.path.empty()))
214
0
                ret->push_back(f.filename);
215
216
0
        return ret;
217
0
    }
218
    //-----------------------------------------------------------------------
219
    FileInfoListPtr ZipArchive::listFileInfo(bool recursive, bool dirs) const
220
0
    {
221
0
        OGRE_LOCK_AUTO_MUTEX;
222
0
        auto ret = std::make_shared<FileInfoList>();
223
0
        for (auto& f : mFileList)
224
0
            if ((dirs == (f.compressedSize == size_t (-1))) &&
225
0
                (recursive || f.path.empty()))
226
0
                ret->push_back(f);
227
228
0
        return ret;
229
0
    }
230
    //-----------------------------------------------------------------------
231
    StringVectorPtr ZipArchive::find(const String& pattern, bool recursive, bool dirs) const
232
0
    {
233
0
        OGRE_LOCK_AUTO_MUTEX;
234
0
        auto ret = std::make_shared<StringVector>();
235
        // If pattern contains a directory name, do a full match
236
0
        bool full_match = (pattern.find ('/') != String::npos) ||
237
0
                          (pattern.find ('\\') != String::npos);
238
0
        bool wildCard = pattern.find('*') != String::npos;
239
            
240
0
        for (auto& f : mFileList)
241
0
            if ((dirs == (f.compressedSize == size_t (-1))) &&
242
0
                (recursive || full_match || wildCard))
243
                // Check basename matches pattern (zip is case insensitive)
244
0
                if (StringUtil::match(full_match ? f.filename : f.basename, pattern, false))
245
0
                    ret->push_back(f.filename);
246
247
0
        return ret;
248
0
    }
249
    //-----------------------------------------------------------------------
250
    FileInfoListPtr ZipArchive::findFileInfo(const String& pattern, 
251
        bool recursive, bool dirs) const
252
0
    {
253
0
        OGRE_LOCK_AUTO_MUTEX;
254
0
        auto ret = std::make_shared<FileInfoList>();
255
        // If pattern contains a directory name, do a full match
256
0
        bool full_match = (pattern.find ('/') != String::npos) ||
257
0
                          (pattern.find ('\\') != String::npos);
258
0
        bool wildCard = pattern.find('*') != String::npos;
259
260
0
        for (auto& f : mFileList)
261
0
            if ((dirs == (f.compressedSize == size_t (-1))) &&
262
0
                (recursive || full_match || wildCard))
263
                // Check name matches pattern (zip is case insensitive)
264
0
                if (StringUtil::match(full_match ? f.filename : f.basename, pattern, false))
265
0
                    ret->push_back(f);
266
267
0
        return ret;
268
0
    }
269
    //-----------------------------------------------------------------------
270
    bool ZipArchive::exists(const String& filename) const
271
0
    {       
272
0
        OGRE_LOCK_AUTO_MUTEX;
273
0
        String cleanName = filename;
274
#if !OGRE_RESOURCEMANAGER_STRICT
275
        if(filename.rfind('/') != String::npos)
276
        {
277
            StringVector tokens = StringUtil::split(filename, "/");
278
            cleanName = tokens[tokens.size() - 1];
279
        }
280
#endif
281
282
0
        return std::find_if(mFileList.begin(), mFileList.end(), [&cleanName](const Ogre::FileInfo& fi) {
283
0
                   return fi.filename == cleanName;
284
0
               }) != mFileList.end();
285
0
    }
286
    //---------------------------------------------------------------------
287
    time_t ZipArchive::getModifiedTime(const String& filename) const
288
0
    {
289
        // Zziplib doesn't yet support getting the modification time of individual files
290
        // so just check the mod time of the zip itself
291
0
        struct stat tagStat;
292
0
        bool ret = (stat(mName.c_str(), &tagStat) == 0);
293
294
0
        if (ret)
295
0
        {
296
0
            return tagStat.st_mtime;
297
0
        }
298
0
        else
299
0
        {
300
0
            return 0;
301
0
        }
302
303
0
    }
304
    //-----------------------------------------------------------------------
305
    //  ZipArchiveFactory
306
    //-----------------------------------------------------------------------
307
    Archive *ZipArchiveFactory::createInstance( const String& name, bool readOnly )
308
0
    {
309
0
        if(!readOnly)
310
0
            return NULL;
311
312
0
        return OGRE_NEW ZipArchive(name, getType());
313
0
    }
314
    //-----------------------------------------------------------------------
315
    const String& ZipArchiveFactory::getType(void) const
316
2
    {
317
2
        static String name = "Zip";
318
2
        return name;
319
2
    }
320
    //-----------------------------------------------------------------------
321
    //-----------------------------------------------------------------------
322
    //  EmbeddedZipArchiveFactory
323
    //-----------------------------------------------------------------------
324
    //-----------------------------------------------------------------------
325
    /// a struct to hold embedded file data
326
    struct EmbeddedFileData
327
    {
328
        const uint8 * fileData;
329
        size_t fileSize;
330
        size_t curPos;
331
        bool isFileOpened;
332
        EmbeddedZipArchiveFactory::DecryptEmbeddedZipFileFunc decryptFunc;
333
    };
334
    //-----------------------------------------------------------------------
335
    /// A type for a map between the file names to file index
336
    typedef std::map<String, EmbeddedFileData> EmbbedFileDataList;
337
338
    namespace {
339
    /// A static list to store the embedded files data
340
    EmbbedFileDataList *gEmbeddedFileDataList;
341
    } // namespace {
342
    //-----------------------------------------------------------------------
343
1
    EmbeddedZipArchiveFactory::EmbeddedZipArchiveFactory() {}
344
1
    EmbeddedZipArchiveFactory::~EmbeddedZipArchiveFactory() {}
345
    //-----------------------------------------------------------------------
346
    Archive *EmbeddedZipArchiveFactory::createInstance( const String& name, bool readOnly )
347
0
    {
348
0
        auto it = gEmbeddedFileDataList->find(name);
349
0
        if(it == gEmbeddedFileDataList->end())
350
0
            return NULL;
351
352
        // TODO: decryptFunc
353
354
0
        return new ZipArchive(name, getType(), it->second.fileData, it->second.fileSize);
355
0
    }
356
    void EmbeddedZipArchiveFactory::destroyInstance(Archive* ptr)
357
0
    {
358
0
        removeEmbbeddedFile(ptr->getName());
359
0
        ZipArchiveFactory::destroyInstance(ptr);
360
0
    }
361
    //-----------------------------------------------------------------------
362
    const String& EmbeddedZipArchiveFactory::getType(void) const
363
2
    {
364
2
        static String name = "EmbeddedZip";
365
2
        return name;
366
2
    }
367
    //-----------------------------------------------------------------------
368
    void EmbeddedZipArchiveFactory::addEmbbeddedFile(const String& name, const uint8 * fileData, 
369
                                        size_t fileSize, DecryptEmbeddedZipFileFunc decryptFunc)
370
0
    {
371
0
        static bool needToInit = true;
372
0
        if(needToInit)
373
0
        {
374
0
            needToInit = false;
375
376
            // we can't be sure when global variables get initialized
377
            // meaning it is possible our list has not been init when this
378
            // function is being called. The solution is to use local
379
            // static members in this function an init the pointers for the
380
            // global here. We know for use that the local static variables
381
            // are create in this stage.
382
0
            static EmbbedFileDataList sEmbbedFileDataList;
383
0
            gEmbeddedFileDataList = &sEmbbedFileDataList;
384
0
        }
385
386
0
        EmbeddedFileData newEmbeddedFileData;
387
0
        newEmbeddedFileData.curPos = 0;
388
0
        newEmbeddedFileData.isFileOpened = false;
389
0
        newEmbeddedFileData.fileData = fileData;
390
0
        newEmbeddedFileData.fileSize = fileSize;
391
0
        newEmbeddedFileData.decryptFunc = decryptFunc;
392
0
        gEmbeddedFileDataList->emplace(name, newEmbeddedFileData);
393
0
    }
394
    //-----------------------------------------------------------------------
395
    void EmbeddedZipArchiveFactory::removeEmbbeddedFile( const String& name )
396
0
    {
397
0
        gEmbeddedFileDataList->erase(name);
398
0
    }
399
}
400
401
#endif