GCC Code Coverage Report
Directory: src/ Exec Total Coverage
File: src/dirs.cpp Lines: 29 157 18.5 %
Date: 2018-09-20 Branches: 18 248 7.3 %

Line Branch Exec Source
1
/*
2
 *  The ManaPlus Client
3
 *  Copyright (C) 2004-2009  The Mana World Development Team
4
 *  Copyright (C) 2009-2010  The Mana Developers
5
 *  Copyright (C) 2011-2018  The ManaPlus Developers
6
 *
7
 *  This file is part of The ManaPlus Client.
8
 *
9
 *  This program is free software; you can redistribute it and/or modify
10
 *  it under the terms of the GNU General Public License as published by
11
 *  the Free Software Foundation; either version 2 of the License, or
12
 *  any later version.
13
 *
14
 *  This program is distributed in the hope that it will be useful,
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *  GNU General Public License for more details.
18
 *
19
 *  You should have received a copy of the GNU General Public License
20
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
#include "dirs.h"
24
25
#include "client.h"
26
#include "configuration.h"
27
#include "logger.h"
28
#include "main.h"
29
#include "settings.h"
30
31
#include "fs/mkdir.h"
32
#include "fs/paths.h"
33
34
#include "fs/virtfs/fs.h"
35
36
#include "utils/base64.h"
37
#if defined(__native_client__) || (defined(ANDROID) && defined(USE_SDL2))
38
#include "fs/files.h"
39
#endif  // defined(__native_client__) || (defined(ANDROID) &&
40
        // defined(USE_SDL2))
41
42
#include "utils/cast.h"
43
#include "utils/gettext.h"
44
45
#ifdef ANDROID
46
#ifdef USE_SDL2
47
#include "main.h"
48
49
#include "render/graphics.h"
50
#endif  // USE_SDL2
51
#endif  // ANDROID
52
53
#ifdef __APPLE__
54
#include <CoreFoundation/CFBundle.h>
55
#endif  // __APPLE__
56
57
#ifdef WIN32
58
PRAGMA48(GCC diagnostic push)
59
PRAGMA48(GCC diagnostic ignored "-Wshadow")
60
#include <SDL_syswm.h>
61
PRAGMA48(GCC diagnostic pop)
62
#include "fs/specialfolder.h"
63
#undef ERROR
64
#endif  // WIN32
65
66
#include <sys/stat.h>
67
68
#include <sstream>
69
70
#include "debug.h"
71
72
#if defined __native_client__
73
#define _nacl_dir std::string("/persistent/manaplus")
74
#endif  // defined __native_client__
75
76
#ifdef ANDROID
77
#ifdef USE_SDL2
78
79
int loadingProgressCounter = 1;
80
81
static void updateProgress(int cnt)
82
{
83
    const int progress = cnt + loadingProgressCounter;
84
    const int h = mainGraphics->mHeight;
85
    mainGraphics->setColor(Color(255, 255, 255, 255));
86
    const int maxSize = mainGraphics->mWidth - 100;
87
    const int width = maxSize * progress / 50;
88
    mainGraphics->fillRectangle(Rect(50, h - 100, width, 50));
89
    mainGraphics->updateScreen();
90
}
91
92
void Dirs::setProgress()
93
{
94
    loadingProgressCounter++;
95
    updateProgress(loadingProgressCounter);
96
}
97
98
static void resetProgress()
99
{
100
    loadingProgressCounter = 0;
101
    updateProgress(loadingProgressCounter);
102
}
103
104
void extractAssets()
105
{
106
    if (!getenv("APPDIR"))
107
    {
108
        logger->log("error: APPDIR is not set!");
109
        return;
110
    }
111
    const std::string fileName = pathJoin(getenv("APPDIR"),
112
        "data.zip");
113
    logger->log("Extracting asset into: " + fileName);
114
    uint8_t *buf = new uint8_t[1000000];
115
116
    FILE *const file = fopen(fileName.c_str(), "w");
117
    for (int f = 0; f < 100; f ++)
118
    {
119
        std::string part = strprintf("manaplus-data.zip%u%u",
120
            CAST_U32(f / 10),
121
            CAST_U32(f % 10));
122
        logger->log("testing asset: " + part);
123
        SDL_RWops *const rw = SDL_RWFromFile(part.c_str(), "r");
124
        if (rw)
125
        {
126
            const int size = SDL_RWsize(rw);
127
            int size2 = SDL_RWread(rw, buf, 1, size);
128
            logger->log("asset size: %d", size2);
129
            fwrite(buf, 1, size2, file);
130
            SDL_RWclose(rw);
131
            Dirs::setProgress();
132
        }
133
        else
134
        {
135
            break;
136
        }
137
    }
138
    fclose(file);
139
140
    const std::string fileName2 = pathJoin(getenv("APPDIR"),
141
        "locale.zip");
142
    FILE *const file2 = fopen(fileName2.c_str(), "w");
143
    SDL_RWops *const rw = SDL_RWFromFile("manaplus-locale.zip", "r");
144
    if (rw)
145
    {
146
        const int size = SDL_RWsize(rw);
147
        int size2 = SDL_RWread(rw, buf, 1, size);
148
        fwrite(buf, 1, size2, file2);
149
        SDL_RWclose(rw);
150
        Dirs::setProgress();
151
    }
152
    fclose(file2);
153
154
    delete [] buf;
155
}
156
157
#endif  // USE_SDL2
158
#endif  // ANDROID
159
160
void Dirs::updateDataPath()
161
{
162
    if (settings.options.dataPath.empty()
163
        && !branding.getStringValue("dataPath").empty())
164
    {
165
        if (isRealPath(branding.getStringValue("dataPath")))
166
        {
167
            settings.options.dataPath = branding.getStringValue("dataPath");
168
        }
169
        else
170
        {
171
            settings.options.dataPath = pathJoin(branding.getDirectory(),
172
                branding.getStringValue("dataPath"));
173
        }
174
        settings.options.skipUpdate = true;
175
    }
176
}
177
178
void Dirs::extractDataDir()
179
{
180
#if defined(ANDROID) && defined(USE_SDL2)
181
    Files::setCopyCallBack(&updateProgress);
182
    resetProgress();
183
    extractAssets();
184
185
    const std::string zipName = pathJoin(getenv("APPDIR"), "data.zip");
186
    const std::string dirName = pathJoin(getenv("APPDIR"), "data");
187
    VirtFs::mountZip2(zipName,
188
        "data",
189
        Append_false);
190
    VirtFs::mountZip2(zipName,
191
        "data/perserver/default",
192
        Append_false);
193
    Files::extractLocale();
194
#endif  // defined(ANDROID) && defined(USE_SDL2)
195
}
196
197
void Dirs::mountDataDir()
198
{
199
    VirtFs::mountDirSilent(PKG_DATADIR "data/perserver/default",
200
        Append_false);
201
    VirtFs::mountDirSilent("data/perserver/default",
202
        Append_false);
203
204
#if defined __APPLE__
205
    CFBundleRef mainBundle = CFBundleGetMainBundle();
206
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
207
    char path[PATH_MAX];
208
    if (!CFURLGetFileSystemRepresentation(resourcesURL,
209
        TRUE,
210
        reinterpret_cast<uint8_t*>(path),
211
        PATH_MAX))
212
    {
213
        fprintf(stderr, "Can't find Resources directory\n");
214
    }
215
    CFRelease(resourcesURL);
216
    std::string path2 = pathJoin(path, "data");
217
    VirtFs::mountDir(pathJoin(path2, "perserver/default"), Append_false);
218
    VirtFs::mountDir(path2, Append_false);
219
// possible this need for support run client from dmg images.
220
//    mPackageDir = path;
221
#endif  // defined __APPLE__
222
223
    VirtFs::mountDirSilent(PKG_DATADIR "data", Append_false);
224
    setPackageDir(PKG_DATADIR "data");
225
    VirtFs::mountDirSilent("data", Append_false);
226
227
#ifdef ANDROID
228
#ifdef USE_SDL2
229
    if (getenv("APPDIR"))
230
    {
231
        const std::string appDir = getenv("APPDIR");
232
        VirtFs::mountDir(appDir + "/data", Append_false);
233
        VirtFs::mountDir(appDir + "/data/perserver/default",
234
            Append_false);
235
    }
236
#endif  // USE_SDL2
237
#endif  // ANDROID
238
239
#if defined __native_client__
240
    VirtFs::mountZip("/http/data.zip", Append_false);
241
    VirtFs::mountZip2("/http/data.zip",
242
        "perserver/default",
243
        Append_false);
244
#endif  // defined __native_client__
245
246
#ifndef WIN32
247
    // Add branding/data to VirtFS search path
248
    if (!settings.options.brandingPath.empty())
249
    {
250
        std::string path = settings.options.brandingPath;
251
252
        // Strip blah.manaplus from the path
253
        const int loc = CAST_S32(path.find_last_of('/'));
254
255
        if (loc > 0)
256
        {
257
            VirtFs::mountDir(path.substr(
258
                0, loc + 1).append("data"),
259
                Append_false);
260
        }
261
    }
262
#endif  // WIN32
263
}
264
265
291
void Dirs::initRootDir()
266
{
267
582
    settings.rootDir = VirtFs::getBaseDir();
268
582
    const std::string portableName = settings.rootDir + "portable.xml";
269
    struct stat statbuf;
270
271

582
    if (stat(portableName.c_str(), &statbuf) == 0 &&
272
        S_ISREG(statbuf.st_mode))
273
    {
274
        std::string dir;
275
        Configuration portable;
276
        portable.init(portableName,
277
            UseVirtFs_false,
278
            SkipError_false);
279
280
        if (settings.options.brandingPath.empty())
281
        {
282
            branding.init(portableName,
283
                UseVirtFs_false,
284
                SkipError_false);
285
            setBrandingDefaults(branding);
286
        }
287
288
        logger->log("Portable file: %s", portableName.c_str());
289
290
        if (settings.options.localDataDir.empty())
291
        {
292
            dir = portable.getValue("dataDir", "");
293
            if (!dir.empty())
294
            {
295
                settings.options.localDataDir = settings.rootDir + dir;
296
                logger->log("Portable data dir: %s",
297
                    settings.options.localDataDir.c_str());
298
            }
299
        }
300
301
        if (settings.options.configDir.empty())
302
        {
303
            dir = portable.getValue("configDir", "");
304
            if (!dir.empty())
305
            {
306
                settings.options.configDir = settings.rootDir + dir;
307
                logger->log("Portable config dir: %s",
308
                    settings.options.configDir.c_str());
309
            }
310
        }
311
312
        if (settings.options.screenshotDir.empty())
313
        {
314
            dir = portable.getValue("screenshotDir", "");
315
            if (!dir.empty())
316
            {
317
                settings.options.screenshotDir = settings.rootDir + dir;
318
                logger->log("Portable screenshot dir: %s",
319
                    settings.options.screenshotDir.c_str());
320
            }
321
        }
322
    }
323
291
}
324
325
/**
326
 * Initializes the home directory. On UNIX and FreeBSD, ~/.mana is used. On
327
 * Windows and other systems we use the current working directory.
328
 */
329
291
void Dirs::initHomeDir()
330
{
331
291
    initLocalDataDir();
332
291
    initTempDir();
333
291
    initConfigDir();
334
291
}
335
336
291
void Dirs::initLocalDataDir()
337
{
338
291
    settings.localDataDir = settings.options.localDataDir;
339
340
291
    if (settings.localDataDir.empty())
341
    {
342
#ifdef __APPLE__
343
        // Use Application Directory instead of .mana
344
        settings.localDataDir = pathJoin(VirtFs::getUserDir(),
345
            "Library/Application Support",
346
            branding.getValue("appName", "ManaPlus"));
347
#elif defined __HAIKU__
348
        settings.localDataDir = pathJoin(VirtFs::getUserDir(),
349
           "config/cache/Mana");
350
#elif defined WIN32
351
        settings.localDataDir = getSpecialFolderLocation(CSIDL_LOCAL_APPDATA);
352
        if (settings.localDataDir.empty())
353
            settings.localDataDir = VirtFs::getUserDir();
354
        settings.localDataDir = pathJoin(settings.localDataDir,
355
            "Mana");
356
#elif defined __ANDROID__
357
        settings.localDataDir = pathJoin(getSdStoragePath(),
358
            branding.getValue("appShort", "ManaPlus"),
359
            "local");
360
#elif defined __native_client__
361
        settings.localDataDir = pathJoin(_nacl_dir, "local");
362
#else  // __APPLE__
363
364

2328
        settings.localDataDir = pathJoin(VirtFs::getUserDir(),
365
291
            ".local/share/mana");
366
#endif  // __APPLE__
367
    }
368
369
291
    if (mkdir_r(settings.localDataDir.c_str()) != 0)
370
    {
371
        // TRANSLATORS: directory creation error
372
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
373
            "Exiting."), settings.localDataDir.c_str()));
374
    }
375
#ifdef USE_PROFILER
376
    Perfomance::init(pathJoin(settings.localDataDir, "profiler.log"));
377
#endif  // USE_PROFILER
378
291
}
379
380
291
void Dirs::initTempDir()
381
{
382
2037
    settings.tempDir = pathJoin(settings.localDataDir, "temp");
383
384
291
    if (mkdir_r(settings.tempDir.c_str()) != 0)
385
    {
386
        // TRANSLATORS: directory creation error
387
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
388
            "Exiting."), settings.tempDir.c_str()));
389
    }
390
//    ResourceManager::deleteFilesInDirectory(settings.tempDir);
391
291
}
392
393
291
void Dirs::initConfigDir()
394
{
395
291
    settings.configDir = settings.options.configDir;
396
397
291
    if (settings.configDir.empty())
398
    {
399
#ifdef __APPLE__
400
        settings.configDir = pathJoin(settings.localDataDir,
401
            branding.getValue("appShort", "mana"));
402
#elif defined __HAIKU__
403
        settings.configDir = pathJoin(VirtFs::getUserDir(),
404
           "config/settings/Mana",
405
           branding.getValue("appName", "ManaPlus"));
406
#elif defined WIN32
407
        settings.configDir = getSpecialFolderLocation(CSIDL_APPDATA);
408
        if (settings.configDir.empty())
409
        {
410
            settings.configDir = settings.localDataDir;
411
        }
412
        else
413
        {
414
            settings.configDir = pathJoin(settings.configDir,
415
                "mana",
416
                branding.getValue("appShort", "mana"));
417
        }
418
#elif defined __ANDROID__
419
        settings.configDir = pathJoin(getSdStoragePath(),
420
            branding.getValue("appShort", "ManaPlus"),
421
            "config");
422
#elif defined __native_client__
423
        settings.configDir = pathJoin(_nacl_dir, "config");
424
#else  // __APPLE__
425
426


2328
        settings.configDir = pathJoin(VirtFs::getUserDir(),
427
            ".config/mana",
428

2619
            branding.getValue("appShort", "mana"));
429
#endif  // __APPLE__
430
431
582
        logger->log("Generating config dir: " + settings.configDir);
432
    }
433
434
291
    if (mkdir_r(settings.configDir.c_str()) != 0)
435
    {
436
        // TRANSLATORS: directory creation error
437
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
438
            "Exiting."), settings.configDir.c_str()));
439
    }
440
291
}
441
442
/**
443
 * Parse the update host and determine the updates directory
444
 * Then verify that the directory exists (creating if needed).
445
 */
446
void Dirs::initUpdatesDir()
447
{
448
    std::stringstream updates;
449
450
    // If updatesHost is currently empty, fill it from config file
451
    if (settings.updateHost.empty())
452
        settings.updateHost = config.getStringValue("updatehost");
453
    if (!checkPath(settings.updateHost))
454
        return;
455
456
    // Don't go out of range int he next check
457
    if (settings.updateHost.length() < 2)
458
    {
459
        if (settings.updatesDir.empty())
460
            settings.updatesDir = pathJoin("updates", settings.serverName);
461
        return;
462
    }
463
464
    const size_t sz = settings.updateHost.size();
465
    // Remove any trailing slash at the end of the update host
466
    if (settings.updateHost.at(sz - 1) == '/')
467
        settings.updateHost.resize(sz - 1);
468
469
    // Parse out any "http://" or "https://", and set the updates directory
470
    const size_t pos = settings.updateHost.find("://");
471
    if (pos != std::string::npos)
472
    {
473
        if (pos + 3 < settings.updateHost.length()
474
            && !settings.updateHost.empty())
475
        {
476
            updates << "updates/" << settings.updateHost.substr(pos + 3);
477
            settings.updatesDir = updates.str();
478
        }
479
        else
480
        {
481
            logger->log("Error: Invalid update host: %s",
482
                settings.updateHost.c_str());
483
            // TRANSLATORS: update server initialisation error
484
            errorMessage = strprintf(_("Invalid update host: %s."),
485
                settings.updateHost.c_str());
486
            client->setState(State::ERROR);
487
        }
488
    }
489
    else
490
    {
491
        logger->log1("Warning: no protocol was specified for the update host");
492
        updates << "updates/" << settings.updateHost;
493
        settings.updatesDir = updates.str();
494
    }
495
496
#ifdef WIN32
497
    if (settings.updatesDir.find(":") != std::string::npos)
498
        replaceAll(settings.updatesDir, ":", "_");
499
#endif  // WIN32
500
501
    const std::string updateDir("/" + settings.updatesDir);
502
503
    // Verify that the updates directory exists. Create if necessary.
504
    if (!VirtFs::isDirectory(updateDir))
505
    {
506
        if (!VirtFs::mkdir(updateDir))
507
        {
508
#if defined WIN32
509
            std::string newDir = pathJoin(settings.localDataDir,
510
                settings.updatesDir);
511
            if (!CreateDirectory(newDir.c_str(), nullptr) &&
512
                GetLastError() != ERROR_ALREADY_EXISTS)
513
            {
514
                logger->log("Error: %s can't be made, but doesn't exist!",
515
                            newDir.c_str());
516
                // TRANSLATORS: update server initialisation error
517
                errorMessage = _("Error creating updates directory!");
518
                client->setState(State::ERROR);
519
            }
520
#else  // defined WIN32
521
522
            logger->log("Error: %s/%s can't be made, but doesn't exist!",
523
                settings.localDataDir.c_str(),
524
                settings.updatesDir.c_str());
525
            // TRANSLATORS: update server initialisation error
526
            errorMessage = _("Error creating updates directory!");
527
            client->setState(State::ERROR);
528
#endif  // defined WIN32
529
        }
530
    }
531
    const std::string updateLocal = pathJoin(updateDir, "local");
532
    const std::string updateFix = pathJoin(updateDir, "fix");
533
    if (!VirtFs::isDirectory(updateLocal))
534
        VirtFs::mkdir(updateLocal);
535
    if (!VirtFs::isDirectory(updateFix))
536
        VirtFs::mkdir(updateFix);
537
}
538
539
void Dirs::initScreenshotDir()
540
{
541
    if (!settings.options.screenshotDir.empty())
542
    {
543
        settings.screenshotDir = settings.options.screenshotDir;
544
        if (mkdir_r(settings.screenshotDir.c_str()) != 0)
545
        {
546
            logger->log(strprintf(
547
                // TRANSLATORS: directory creation error
548
                _("Error: %s doesn't exist and can't be created! "
549
                "Exiting."), settings.screenshotDir.c_str()));
550
        }
551
    }
552
    else if (settings.screenshotDir.empty())
553
    {
554
#ifdef __native_client__
555
        settings.screenshotDir = pathJoin(_nacl_dir, "screenshots/");
556
#else  // __native_client__
557
        settings.screenshotDir = decodeBase64String(
558
            config.getStringValue("screenshotDirectory3"));
559
        if (settings.screenshotDir.empty())
560
        {
561
#ifdef __ANDROID__
562
            settings.screenshotDir = getSdStoragePath()
563
                + std::string("/images");
564
565
            if (mkdir_r(settings.screenshotDir.c_str()))
566
            {
567
                logger->log(strprintf(
568
                    // TRANSLATORS: directory creation error
569
                    _("Error: %s doesn't exist and can't be created! "
570
                    "Exiting."), settings.screenshotDir.c_str()));
571
            }
572
#else  // ANDROID
573
            settings.screenshotDir = getPicturesDir();
574
#endif  // ANDROID
575
            if (config.getBoolValue("useScreenshotDirectorySuffix"))
576
            {
577
                const std::string configScreenshotSuffix =
578
                    branding.getValue("screenshots", "ManaPlus");
579
580
                if (!configScreenshotSuffix.empty())
581
                {
582
                    settings.screenshotDir = pathJoin(settings.screenshotDir,
583
                        configScreenshotSuffix);
584
                }
585
            }
586
            config.setValue("screenshotDirectory3",
587
                encodeBase64String(settings.screenshotDir));
588
        }
589
#endif  // __native_client__
590
    }
591
    logger->log("screenshotDirectory: " + settings.screenshotDir);
592
}
593
594
void Dirs::initUsersDir()
595
{
596
    settings.usersDir = settings.serverConfigDir + "/users/";
597
    if (mkdir_r(settings.usersDir.c_str()) != 0)
598
    {
599
        // TRANSLATORS: directory creation error
600
        logger->error(strprintf(_("%s doesn't exist and can't be created!"),
601
            settings.usersDir.c_str()));
602
    }
603
604
    settings.npcsDir = settings.serverConfigDir + "/npcs/";
605
    if (mkdir_r(settings.npcsDir.c_str()) != 0)
606
    {
607
        // TRANSLATORS: directory creation error
608
        logger->error(strprintf(_("%s doesn't exist and can't be created!"),
609
            settings.npcsDir.c_str()));
610
    }
611
612
    settings.usersIdDir = settings.serverConfigDir + "/usersid/";
613
    if (mkdir_r(settings.usersIdDir.c_str()) != 0)
614
    {
615
        // TRANSLATORS: directory creation error
616
        logger->error(strprintf(_("%s doesn't exist and can't be created!"),
617
            settings.usersIdDir.c_str()));
618
    }
619
}