File: syncthingconfig.cpp

package info (click to toggle)
syncthingtray 1.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,804 kB
  • sloc: cpp: 31,085; xml: 1,694; java: 570; sh: 81; javascript: 53; makefile: 25
file content (247 lines) | stat: -rw-r--r-- 8,244 bytes parent folder | download
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
#include "./syncthingconfig.h"
#include "./utils.h"

#include "resources/config.h"

#include <qtutilities/misc/compat.h>

#include <QFile>
#include <QHash>
#include <QStandardPaths>
#include <QStringBuilder>
#include <QXmlStreamReader>

#include <QJsonObject>

namespace Data {

/*!
 * \struct SyncthingConfig
 * \brief The SyncthingConfig struct holds the configuration of the local Syncthing instance read from config.xml in the Syncthing home directory.
 * \remarks Only a few fields are required since most of the Syncthing config can be accessed via SyncthingConnection class.
 */

/*!
 * \brief Locates the file with the specified \a fileName in Syncthing's config directory.
 * \remarks The lookup within QStandardPaths::RuntimeLocation is mainly for macOS where the full path
 *          is "$HOME/Library/Application Support/Syncthing/config.xml".
 */
QString SyncthingConfig::locateConfigFile(const QString &fileName)
{
    // check override via environment variable
    auto path = qEnvironmentVariable(PROJECT_VARNAME_UPPER "_SYNCTHING_CONFIG_DIR");
    if (!path.isEmpty()) {
        if (!QFile::exists(path = path % QChar('/') % fileName)) {
            path.clear();
        }
        return path;
    }

    // check usual standard locations
    static const QString casings[] = { QStringLiteral("syncthing/"), QStringLiteral("Syncthing/") };
    static const QStandardPaths::StandardLocation locations[] = { QStandardPaths::GenericConfigLocation, QStandardPaths::RuntimeLocation };
    for (const auto location : locations) {
        for (const auto &casing : casings) {
            if (!(path = QStandardPaths::locate(location, casing + fileName)).isEmpty()) {
                return path;
            }
        }
    }

    // check state dir used by Syncthing on Unix systems as of v1.27.0 (commit b5082f6af8b0a70afd3bc42977dad26920e72b68)
#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
    if (!(path = qEnvironmentVariable("XDG_STATE_HOME")).isEmpty()) {
        if (QFile::exists(path = path % QStringLiteral("/syncthing/") % fileName)) {
            return path;
        }
    }
    if (!(path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation)).isEmpty()) {
        if (QFile::exists(path = path % QStringLiteral("/.local/state/syncthing/") % fileName)) {
            return path;
        }
    }
#endif

    path.clear();
    return path;
}

/*!
 * \brief Locates Syncthing's main config file ("config.xml").
 */
QString SyncthingConfig::locateConfigFile()
{
    return locateConfigFile(QStringLiteral("config.xml"));
}

/*!
 * \brief Locates Syncthing's GUI HTTPS certificate.
 */
QString SyncthingConfig::locateHttpsCertificate()
{
    return locateConfigFile(QStringLiteral("https-cert.pem"));
}

/*!
 * \brief Converts a single text value to a JSON value guessing the type.
 */
static QJsonValue xmlValueToJsonValue(QStringView value)
{
    if (value == QLatin1String("true")) {
        return QJsonValue(true);
    } else if (value == QLatin1String("false")) {
        return QJsonValue(false);
    }
    auto isNumber = false;
    auto number = value.toDouble(&isNumber);
    return isNumber ? QJsonValue(number) : QJsonValue(value.toString());
}

/*!
 * \brief Adds current attributes form \a xmlReader to \a jsonObject.
 */
static void xmlAttributesToJsonObject(QXmlStreamReader &xmlReader, QJsonObject &jsonObject)
{
    for (const auto &attribute : xmlReader.attributes()) {
        jsonObject.insert(attribute.name(), xmlValueToJsonValue(attribute.value()));
    }
}

/*!
 * \brief Adds the current element of \a xmlReader to \a object.
 * \remarks The tokenType() of \a xmlReader is supposed to be QXmlStreamReader::StartElement.
 */
static void xmlElementToJsonValue(QXmlStreamReader &xmlReader, QJsonObject &object)
{
    static const auto arrayElements = QHash<QString, QString>{
        { QStringLiteral("device"), QStringLiteral("devices") },
        { QStringLiteral("address"), QStringLiteral("addresses") },
    };
    auto name = xmlReader.name().toString();
    auto arrayName = arrayElements.find(name);
    auto text = QString();
    auto nestedObject = QJsonObject();
    auto valid = true;
    xmlAttributesToJsonObject(xmlReader, nestedObject);
    while (valid) {
        switch (xmlReader.readNext()) {
        case QXmlStreamReader::StartElement:
            xmlAttributesToJsonObject(xmlReader, nestedObject);
            xmlElementToJsonValue(xmlReader, nestedObject);
            break;
        case QXmlStreamReader::Characters:
            text.append(xmlReader.text());
            break;
        case QXmlStreamReader::Invalid:
        case QXmlStreamReader::EndDocument:
        case QXmlStreamReader::EndElement:
            valid = false;
            break;
        default:;
        }
    }
    if (arrayName == arrayElements.cend()) {
        object.insert(std::move(name), nestedObject.isEmpty() ? xmlValueToJsonValue(text) : std::move(nestedObject));
    } else {
        if (*arrayName == QLatin1String("devices")) {
            nestedObject.insert(QStringLiteral("deviceID"), nestedObject.take(QLatin1String("id")));
        }
        auto valueRef = object[*arrayName];
        auto array = valueRef.isArray() ? valueRef.toArray() : QJsonArray();
        array.append(nestedObject.isEmpty() ? xmlValueToJsonValue(text) : std::move(nestedObject));
        valueRef = array;
    }
}

/*!
 * \brief Converts the current sub-tree of \a xmlReader to a QJsonObject.
 * \remarks The tokenType() of \a xmlReader is supposed to be QXmlStreamReader::StartElement.
 */
static QJsonObject xmlToJson(QXmlStreamReader &xmlReader, bool convertDeviceId)
{
    auto json = QJsonObject();
    xmlAttributesToJsonObject(xmlReader, json);
    while (xmlReader.readNextStartElement()) {
        xmlElementToJsonValue(xmlReader, json);
    }
    if (convertDeviceId) {
        json.insert(QStringLiteral("deviceID"), json.take(QLatin1String("id")));
    }
    return json;
}

/*!
 * \brief Reads the configuration at the specified \a configFilePath.
 * \param details Whether details should be populates as well.
 */
bool SyncthingConfig::restore(const QString &configFilePath, bool detailed)
{
    auto configFile = QFile(configFilePath);
    if (!configFile.open(QFile::ReadOnly)) {
        return false;
    }

    auto xmlReader = QXmlStreamReader(&configFile);
    auto ok = false;
    auto *const details = detailed ? &this->details.emplace() : nullptr;
#include <qtutilities/misc/xmlparsermacros.h>
    children
    {
        // only version 16 supported, try to parse other versions anyway since the changes might not affect
        // the few parts read here
        version = attribute("version").toString();
        children
        {
            iftag("gui")
            {
                ok = true;
                guiEnabled = attributeFlag("enabled");
                guiEnforcesSecureConnection = attributeFlag("tls");
                children
                {
                    iftag("address")
                    {
                        guiAddress = text;
                    }
                    eliftag("user")
                    {
                        guiUser = text;
                    }
                    eliftag("password")
                    {
                        guiPasswordHash = text;
                    }
                    eliftag("apikey")
                    {
                        guiApiKey = text;
                    }
                    else_skip
                }
            }
            eliftag("folder")
            {
                if (details) {
                    details->folders.append(xmlToJson(xmlReader, false));
                }
                else_skip
            }
            eliftag("device")
            {
                if (details) {
                    details->devices.append(xmlToJson(xmlReader, true));
                }
                else_skip
            }
            else_skip
        }
    }
#include <qtutilities/misc/undefxmlparsermacros.h>
    return ok;
}

QString SyncthingConfig::syncthingUrl() const
{
    return (guiEnforcesSecureConnection || !isLocal(stripPort(guiAddress)) ? QStringLiteral("https://") : QStringLiteral("http://")) + guiAddress;
}

} // namespace Data