GCC Code Coverage Report
Directory: src/ Exec Total Coverage
File: src/dirs.cpp Lines: 28 139 20.1 %
Date: 2017-11-29 Branches: 20 272 7.4 %

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-2017  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));
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
536
void Dirs::initRootDir()
266
{
267
1072
    settings.rootDir = VirtFs::getBaseDir();
268
1072
    const std::string portableName = settings.rootDir + "portable.xml";
269
    struct stat statbuf;
270
271

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


4288
        settings.localDataDir = pathJoin(VirtFs::getUserDir(),
361
            ".local/share/mana");
362
#endif  // __APPLE__
363
    }
364
365
536
    if (mkdir_r(settings.localDataDir.c_str()) != 0)
366
    {
367
        // TRANSLATORS: directory creation error
368
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
369
            "Exiting."), settings.localDataDir.c_str()));
370
    }
371
#ifdef USE_PROFILER
372
    Perfomance::init(pathJoin(settings.localDataDir, "profiler.log"));
373
#endif  // USE_PROFILER
374
536
}
375
376
536
void Dirs::initTempDir()
377
{
378

3752
    settings.tempDir = pathJoin(settings.localDataDir, "temp");
379
380
536
    if (mkdir_r(settings.tempDir.c_str()) != 0)
381
    {
382
        // TRANSLATORS: directory creation error
383
        logger->error(strprintf(_("%s doesn't exist and can't be created! "
384
            "Exiting."), settings.tempDir.c_str()));
385
    }
386
//    ResourceManager::deleteFilesInDirectory(settings.tempDir);
387
536
}
388
389
536
void Dirs::initConfigDir()
390
{
391
536
    settings.configDir = settings.options.configDir;
392
393
536
    if (settings.configDir.empty())
394
    {
395
#ifdef __APPLE__
396
        settings.configDir = pathJoin(settings.localDataDir,
397
            branding.getValue("appShort", "mana"));
398
#elif defined __HAIKU__
399
        settings.configDir = pathJoin(VirtFs::getUserDir(),
400
           "config/settings/Mana",
401
           branding.getValue("appName", "ManaPlus"));
402
#elif defined WIN32
403
        settings.configDir = getSpecialFolderLocation(CSIDL_APPDATA);
404
        if (settings.configDir.empty())
405
        {
406
            settings.configDir = settings.localDataDir;
407
        }
408
        else
409
        {
410
            settings.configDir = pathJoin(settings.configDir,
411
                "mana",
412
                branding.getValue("appShort", "mana"));
413
        }
414
#elif defined __ANDROID__
415
        settings.configDir = pathJoin(getSdStoragePath(),
416
            branding.getValue("appShort", "ManaPlus"),
417
            "config");
418
#elif defined __native_client__
419
        settings.configDir = pathJoin(_nacl_dir, "config");
420
#else  // __APPLE__
421
422


4288
        settings.configDir = pathJoin(VirtFs::getUserDir(),
423
            ".config/mana",
424

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