aboutsummaryrefslogtreecommitdiffstats
path: root/alc/alconfig.cpp
blob: c99367255ca5ebd35a9990d912cdd9b5e5e6e6dc (plain)
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
339
340
341
342
343
344
345
346
347
348
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/**
 * OpenAL cross platform audio library
 * Copyright (C) 1999-2007 by authors.
 * This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 *  Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the
 *  Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * Or go to http://www.gnu.org/copyleft/lgpl.html
 */

#include "config.h"

#include "alconfig.h"

#ifdef _WIN32
#include <windows.h>
#include <shlobj.h>
#endif
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#endif

#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <istream>
#include <limits>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "alfstream.h"
#include "alstring.h"
#include "core/helpers.h"
#include "core/logging.h"
#include "strutils.h"

#if defined(ALSOFT_UWP)
#include <winrt/Windows.Media.Core.h> // !!This is important!!
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
using namespace winrt;
#endif

namespace {

struct ConfigEntry {
    std::string key;
    std::string value;
};
std::vector<ConfigEntry> ConfOpts;


std::string &lstrip(std::string &line)
{
    size_t pos{0};
    while(pos < line.length() && std::isspace(line[pos]))
        ++pos;
    line.erase(0, pos);
    return line;
}

bool readline(std::istream &f, std::string &output)
{
    while(f.good() && f.peek() == '\n')
        f.ignore();

    return std::getline(f, output) && !output.empty();
}

std::string expdup(std::string_view str)
{
    std::string output;

    while(!str.empty())
    {
        if(auto nextpos = str.find('$'))
        {
            output += str.substr(0, nextpos);
            if(nextpos == std::string_view::npos)
                break;

            str.remove_prefix(nextpos);
        }

        str.remove_prefix(1);
        if(str.front() == '$')
        {
            output += '$';
            str.remove_prefix(1);
            continue;
        }

        const bool hasbraces{str.front() == '{'};
        if(hasbraces) str.remove_prefix(1);

        size_t envend{0};
        while(std::isalnum(str[envend]) || str[envend] == '_')
            ++envend;
        if(hasbraces && str[envend] != '}')
            continue;
        const std::string envname{str.substr(0, envend)};
        if(hasbraces) ++envend;
        str.remove_prefix(envend);

        if(auto envval = al::getenv(envname.c_str()))
            output += *envval;
    }

    return output;
}

void LoadConfigFromFile(std::istream &f)
{
    std::string curSection;
    std::string buffer;

    while(readline(f, buffer))
    {
        if(lstrip(buffer).empty())
            continue;

        if(buffer[0] == '[')
        {
            auto endpos = buffer.find(']', 1);
            if(endpos == 1 || endpos == std::string::npos)
            {
                ERR(" config parse error: bad line \"%s\"\n", buffer.c_str());
                continue;
            }
            if(buffer[endpos+1] != '\0')
            {
                size_t last{endpos+1};
                while(last < buffer.size() && std::isspace(buffer[last]))
                    ++last;

                if(last < buffer.size() && buffer[last] != '#')
                {
                    ERR(" config parse error: bad line \"%s\"\n", buffer.c_str());
                    continue;
                }
            }

            auto section = std::string_view{buffer}.substr(1, endpos-1);
            auto generalName = std::string_view{"general"};

            curSection.clear();
            if(section.size() != generalName.size()
                || al::strncasecmp(section.data(), generalName.data(), section.size()) != 0)
            {
                do {
                    auto nextp = section.find('%');
                    if(nextp == std::string_view::npos)
                    {
                        curSection += section;
                        break;
                    }

                    curSection += section.substr(0, nextp);
                    section.remove_prefix(nextp);

                    if(((section[1] >= '0' && section[1] <= '9') ||
                        (section[1] >= 'a' && section[1] <= 'f') ||
                        (section[1] >= 'A' && section[1] <= 'F')) &&
                       ((section[2] >= '0' && section[2] <= '9') ||
                        (section[2] >= 'a' && section[2] <= 'f') ||
                        (section[2] >= 'A' && section[2] <= 'F')))
                    {
                        int b{0};
                        if(section[1] >= '0' && section[1] <= '9')
                            b = (section[1]-'0') << 4;
                        else if(section[1] >= 'a' && section[1] <= 'f')
                            b = (section[1]-'a'+0xa) << 4;
                        else if(section[1] >= 'A' && section[1] <= 'F')
                            b = (section[1]-'A'+0x0a) << 4;
                        if(section[2] >= '0' && section[2] <= '9')
                            b |= (section[2]-'0');
                        else if(section[2] >= 'a' && section[2] <= 'f')
                            b |= (section[2]-'a'+0xa);
                        else if(section[2] >= 'A' && section[2] <= 'F')
                            b |= (section[2]-'A'+0x0a);
                        curSection += static_cast<char>(b);
                        section.remove_prefix(3);
                    }
                    else if(section[1] == '%')
                    {
                        curSection += '%';
                        section.remove_prefix(2);
                    }
                    else
                    {
                        curSection += '%';
                        section.remove_prefix(1);
                    }
                } while(!section.empty());
            }

            continue;
        }

        auto cmtpos = std::min(buffer.find('#'), buffer.size());
        while(cmtpos > 0 && std::isspace(buffer[cmtpos-1]))
            --cmtpos;
        if(!cmtpos) continue;
        buffer.erase(cmtpos);

        auto sep = buffer.find('=');
        if(sep == std::string::npos)
        {
            ERR(" config parse error: malformed option line: \"%s\"\n", buffer.c_str());
            continue;
        }
        auto keypart = std::string_view{buffer}.substr(0, sep++);
        while(!keypart.empty() && std::isspace(keypart.back()))
            keypart.remove_suffix(1);
        if(keypart.empty())
        {
            ERR(" config parse error: malformed option line: \"%s\"\n", buffer.c_str());
            continue;
        }
        auto valpart = std::string_view{buffer}.substr(sep);
        while(!valpart.empty() && std::isspace(valpart.front()))
            valpart.remove_prefix(1);

        std::string fullKey;
        if(!curSection.empty())
        {
            fullKey += curSection;
            fullKey += '/';
        }
        fullKey += keypart;

        if(valpart.size() > std::numeric_limits<int>::max())
        {
            ERR(" config parse error: value too long in line \"%s\"\n", buffer.c_str());
            continue;
        }
        if(valpart.size() > 1)
        {
            if((valpart.front() == '"' && valpart.back() == '"')
                || (valpart.front() == '\'' && valpart.back() == '\''))
            {
                valpart.remove_prefix(1);
                valpart.remove_suffix(1);
            }
        }

        TRACE(" setting '%s' = '%.*s'\n", fullKey.c_str(), static_cast<int>(valpart.size()),
            valpart.data());

        /* Check if we already have this option set */
        auto find_key = [&fullKey](const ConfigEntry &entry) -> bool
        { return entry.key == fullKey; };
        auto ent = std::find_if(ConfOpts.begin(), ConfOpts.end(), find_key);
        if(ent != ConfOpts.end())
        {
            if(!valpart.empty())
                ent->value = expdup(valpart);
            else
                ConfOpts.erase(ent);
        }
        else if(!valpart.empty())
            ConfOpts.emplace_back(ConfigEntry{std::move(fullKey), expdup(valpart)});
    }
    ConfOpts.shrink_to_fit();
}

const char *GetConfigValue(const char *devName, const char *blockName, const char *keyName)
{
    if(!keyName)
        return nullptr;

    std::string key;
    if(blockName && al::strcasecmp(blockName, "general") != 0)
    {
        key = blockName;
        if(devName)
        {
            key += '/';
            key += devName;
        }
        key += '/';
        key += keyName;
    }
    else
    {
        if(devName)
        {
            key = devName;
            key += '/';
        }
        key += keyName;
    }

    auto iter = std::find_if(ConfOpts.cbegin(), ConfOpts.cend(),
        [&key](const ConfigEntry &entry) -> bool
        { return entry.key == key; });
    if(iter != ConfOpts.cend())
    {
        TRACE("Found option %s = \"%s\"\n", key.c_str(), iter->value.c_str());
        if(!iter->value.empty())
            return iter->value.c_str();
        return nullptr;
    }

    if(!devName)
        return nullptr;
    return GetConfigValue(nullptr, blockName, keyName);
}

} // namespace


#ifdef _WIN32
void ReadALConfig()
{
#if !defined(_GAMING_XBOX)
    {
#if !defined(ALSOFT_UWP)
        WCHAR buffer[MAX_PATH];
        if (!SHGetSpecialFolderPathW(nullptr, buffer, CSIDL_APPDATA, FALSE))
            return;
#else
        winrt::Windows::Storage::ApplicationDataContainer localSettings = winrt::Windows::Storage::ApplicationData::Current().LocalSettings();
        auto buffer = Windows::Storage::ApplicationData::Current().RoamingFolder().Path();
#endif
        std::string filepath{wstr_to_utf8(buffer)};
        filepath += "\\alsoft.ini";

        TRACE("Loading config %s...\n", filepath.c_str());
        al::ifstream f{filepath};
        if(f.is_open())
            LoadConfigFromFile(f);
    }
#endif


    std::string ppath{GetProcBinary().path};
    if(!ppath.empty())
    {
        ppath += "\\alsoft.ini";
        TRACE("Loading config %s...\n", ppath.c_str());
        al::ifstream f{ppath};
        if(f.is_open())
            LoadConfigFromFile(f);
    }

    if(auto confpath = al::getenv(L"ALSOFT_CONF"))
    {
        TRACE("Loading config %s...\n", wstr_to_utf8(confpath->c_str()).c_str());
        al::ifstream f{*confpath};
        if(f.is_open())
            LoadConfigFromFile(f);
    }
}

#else

void ReadALConfig()
{
    const char *str{"/etc/openal/alsoft.conf"};

    TRACE("Loading config %s...\n", str);
    al::ifstream f{str};
    if(f.is_open())
        LoadConfigFromFile(f);
    f.close();

    std::string confpaths{al::getenv("XDG_CONFIG_DIRS").value_or("/etc/xdg")};
    /* Go through the list in reverse, since "the order of base directories
     * denotes their importance; the first directory listed is the most
     * important". Ergo, we need to load the settings from the later dirs
     * first so that the settings in the earlier dirs override them.
     */
    std::string fname;
    while(!confpaths.empty())
    {
        auto next = confpaths.find_last_of(':');
        if(next < confpaths.length())
        {
            fname = confpaths.substr(next+1);
            confpaths.erase(next);
        }
        else
        {
            fname = confpaths;
            confpaths.clear();
        }

        if(fname.empty() || fname.front() != '/')
            WARN("Ignoring XDG config dir: %s\n", fname.c_str());
        else
        {
            if(fname.back() != '/') fname += "/alsoft.conf";
            else fname += "alsoft.conf";

            TRACE("Loading config %s...\n", fname.c_str());
            f = al::ifstream{fname};
            if(f.is_open())
                LoadConfigFromFile(f);
        }
        fname.clear();
    }

#ifdef __APPLE__
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    if(mainBundle)
    {
        unsigned char fileName[PATH_MAX];
        CFURLRef configURL;

        if((configURL=CFBundleCopyResourceURL(mainBundle, CFSTR(".alsoftrc"), CFSTR(""), nullptr)) &&
           CFURLGetFileSystemRepresentation(configURL, true, fileName, sizeof(fileName)))
        {
            f = al::ifstream{reinterpret_cast<char*>(fileName)};
            if(f.is_open())
                LoadConfigFromFile(f);
        }
    }
#endif

    if(auto homedir = al::getenv("HOME"))
    {
        fname = *homedir;
        if(fname.back() != '/') fname += "/.alsoftrc";
        else fname += ".alsoftrc";

        TRACE("Loading config %s...\n", fname.c_str());
        f = al::ifstream{fname};
        if(f.is_open())
            LoadConfigFromFile(f);
    }

    if(auto configdir = al::getenv("XDG_CONFIG_HOME"))
    {
        fname = *configdir;
        if(fname.back() != '/') fname += "/alsoft.conf";
        else fname += "alsoft.conf";
    }
    else
    {
        fname.clear();
        if(auto homedir = al::getenv("HOME"))
        {
            fname = *homedir;
            if(fname.back() != '/') fname += "/.config/alsoft.conf";
            else fname += ".config/alsoft.conf";
        }
    }
    if(!fname.empty())
    {
        TRACE("Loading config %s...\n", fname.c_str());
        f = al::ifstream{fname};
        if(f.is_open())
            LoadConfigFromFile(f);
    }

    std::string ppath{GetProcBinary().path};
    if(!ppath.empty())
    {
        if(ppath.back() != '/') ppath += "/alsoft.conf";
        else ppath += "alsoft.conf";

        TRACE("Loading config %s...\n", ppath.c_str());
        f = al::ifstream{ppath};
        if(f.is_open())
            LoadConfigFromFile(f);
    }

    if(auto confname = al::getenv("ALSOFT_CONF"))
    {
        TRACE("Loading config %s...\n", confname->c_str());
        f = al::ifstream{*confname};
        if(f.is_open())
            LoadConfigFromFile(f);
    }
}
#endif

std::optional<std::string> ConfigValueStr(const char *devName, const char *blockName, const char *keyName)
{
    if(const char *val{GetConfigValue(devName, blockName, keyName)})
        return val;
    return std::nullopt;
}

std::optional<int> ConfigValueInt(const char *devName, const char *blockName, const char *keyName)
{
    if(const char *val{GetConfigValue(devName, blockName, keyName)})
        return static_cast<int>(std::strtol(val, nullptr, 0));
    return std::nullopt;
}

std::optional<unsigned int> ConfigValueUInt(const char *devName, const char *blockName, const char *keyName)
{
    if(const char *val{GetConfigValue(devName, blockName, keyName)})
        return static_cast<unsigned int>(std::strtoul(val, nullptr, 0));
    return std::nullopt;
}

std::optional<float> ConfigValueFloat(const char *devName, const char *blockName, const char *keyName)
{
    if(const char *val{GetConfigValue(devName, blockName, keyName)})
        return std::strtof(val, nullptr);
    return std::nullopt;
}

std::optional<bool> ConfigValueBool(const char *devName, const char *blockName, const char *keyName)
{
    if(const char *val{GetConfigValue(devName, blockName, keyName)})
        return al::strcasecmp(val, "on") == 0 || al::strcasecmp(val, "yes") == 0
            || al::strcasecmp(val, "true")==0 || atoi(val) != 0;
    return std::nullopt;
}

bool GetConfigValueBool(const char *devName, const char *blockName, const char *keyName, bool def)
{
    if(const char *val{GetConfigValue(devName, blockName, keyName)})
        return (al::strcasecmp(val, "on") == 0 || al::strcasecmp(val, "yes") == 0
            || al::strcasecmp(val, "true") == 0 || atoi(val) != 0);
    return def;
}