QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
templateio.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "templateio.h"
9#include "filecontent.h"
10#include "util.h"
11
12#include <QDebug>
13#include <QDir>
14#include <QFile>
15#include <QRegularExpression>
16#include <QSaveFile>
17#include <QStringConverter>
18#include <QTextStream>
19#include <algorithm>
20#include <optional>
21#include <utility>
22
23namespace {
24
26constexpr qint64 kMaxTemplateFileBytes = qint64{64} * 1024;
27
37auto readTemplateFile(const QString &path) -> std::optional<QString> {
38 QFile file;
39 if (!Util::openRegularFile(path, file)) {
40 return std::nullopt;
41 }
42 const QByteArray bytes = file.read(kMaxTemplateFileBytes + 1);
43 if (bytes.size() > kMaxTemplateFileBytes) {
44 qWarning() << "Ignoring" << path << "; a template file is at most"
45 << kMaxTemplateFileBytes << "bytes";
46 return std::nullopt;
47 }
48 // QTextStream skipped a UTF-8 byte order mark (older Notepad writes one);
49 // fromUtf8() keeps it as U+FEFF, which trimmed() leaves in place.
50 const QByteArray bom("\xEF\xBB\xBF");
51 return QString::fromUtf8(bytes.startsWith(bom) ? bytes.mid(bom.size())
52 : bytes);
53}
54
57auto sectionHeader(const QString &line) -> std::optional<QString> {
58 if (!line.startsWith('[') || !line.endsWith(']')) {
59 return std::nullopt;
60 }
61 return line.mid(1, line.length() - 2).trimmed();
62}
63
65auto defaultTemplateIn(const QDir &dir) -> QString {
66 const std::optional<QString> contents =
67 readTemplateFile(dir.filePath(".default_template"));
68 if (!contents) {
69 return {};
70 }
71 const QString name = contents->section(QLatin1Char('\n'), 0, 0).trimmed();
72 return name.startsWith('#') ? QString() : name;
73}
74
75} // namespace
76
77auto TemplateIO::readTemplates(const QString &storePath)
78 -> QHash<QString, QStringList> {
79 QHash<QString, QStringList> result;
80 std::optional<QString> contents =
81 readTemplateFile(QDir(storePath).filePath(".templates"));
82 if (!contents) {
83 return result;
84 }
85 QTextStream in(&*contents, QIODevice::ReadOnly);
86 // No section before the first header, nor for an empty `[]`: fields there
87 // belong to nothing and are dropped.
88 std::optional<QString> section;
89 QStringList fields;
90 const auto flush = [&] {
91 if (section) {
92 result.insert(*section, fields);
93 }
94 fields.clear();
95 };
96 while (!in.atEnd()) {
97 const QString line = in.readLine().trimmed();
98 if (const std::optional<QString> header = sectionHeader(line)) {
99 flush();
100 section = header->isEmpty() ? std::nullopt : header;
101 if (!section) {
102 qWarning()
103 << "Empty template section in .templates file, ignoring fields";
104 }
105 } else if (section && !line.isEmpty() && !line.startsWith('#')) {
106 fields.append(line);
107 }
108 }
109 flush();
110 return result;
111}
112
113auto TemplateIO::secretFieldsIn(const QString &templateText) -> QStringList {
114 static const QRegularExpression marker(
115 QStringLiteral("^#\\s*secret\\s*:(.*)$"),
116 QRegularExpression::CaseInsensitiveOption);
117 QStringList names;
118 const QStringList lines = templateText.split(QLatin1Char('\n'));
119 for (const QString &line : lines) {
120 const QRegularExpressionMatch match = marker.match(line.trimmed());
121 if (!match.hasMatch()) {
122 continue;
123 }
124 const QStringList listed = match.captured(1).split(QLatin1Char(','));
125 for (const QString &name : listed) {
126 const QString trimmed = name.trimmed();
127 if (!trimmed.isEmpty()) {
128 names << trimmed;
129 }
130 }
131 }
132 return names;
133}
134
135auto TemplateIO::readSecretFields(const QString &storePath) -> QStringList {
136 const std::optional<QString> contents =
137 readTemplateFile(QDir(storePath).filePath(".templates"));
138 return contents ? secretFieldsIn(*contents) : QStringList();
139}
140
141auto TemplateIO::fieldsIn(const QString &templateText) -> QStringList {
142 // Every field becomes a row of widgets in the password dialog, built with
143 // a focus chain that grows quadratically: a store's 64 KiB .templates of
144 // one-letter lines froze Add password for half a minute. A template gets
145 // as many fields as an entry may have.
146 QStringList fields;
147 int named = 0;
148 const QStringList lines = templateText.split(QLatin1Char('\n'));
149 for (const QString &line : lines) {
150 if (line.trimmed().startsWith(QLatin1Char('#'))) {
151 continue;
152 }
153 // Counted as setTemplate() builds rows: for every line not empty, a
154 // line of blanks too.
155 if (!line.isEmpty()) {
156 if (named == FileContent::kMaxNamedFields) {
157 qWarning() << "Template has more than" << FileContent::kMaxNamedFields
158 << "fields; ignoring the rest";
159 break;
160 }
161 ++named;
162 }
163 fields.append(line);
164 }
165 return fields;
166}
167
168auto TemplateIO::writeTemplates(const QString &storePath,
169 const QHash<QString, QStringList> &templates)
170 -> bool {
171 QSaveFile saveFile(QDir(storePath).filePath(".templates"));
172 if (!saveFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
173 return false;
174 }
175 QTextStream out(&saveFile);
176 out.setEncoding(QStringConverter::Utf8);
177 out << "# QtPass templates configuration\n";
178 out << "# Format: INI-style with [template_name] sections,\n";
179 out << "# followed by field names (one per line)\n\n";
180
181 QStringList sortedKeys = templates.keys();
182 std::sort(sortedKeys.begin(), sortedKeys.end());
183 for (const QString &key : std::as_const(sortedKeys)) {
184 out << "[" << key << "]\n";
185 for (const QString &field : templates.value(key)) {
186 out << field << "\n";
187 }
188 out << "\n";
189 }
190 out.flush();
191 if (out.status() != QTextStream::Ok) {
192 return false;
193 }
194 return saveFile.commit();
195}
196
197auto TemplateIO::getFolderTemplate(const QString &folderPath,
198 const QString &storePath) -> QString {
199 const QString store = QDir::cleanPath(QDir(storePath).absolutePath());
200 // Only the store root and its descendants are probed for
201 // .default_template; a path outside the store opens nothing.
202 const auto inStore = [&store](const QString &path) {
203 return path == store ||
204 (path.startsWith(store) && path.length() > store.length() &&
205 path.at(store.length()) == QChar('/'));
206 };
207 QDir dir(folderPath);
208 while (inStore(QDir::cleanPath(dir.absolutePath()))) {
209 const QString name = defaultTemplateIn(dir);
210 if (!name.isEmpty()) {
211 return name;
212 }
213 if (QDir::cleanPath(dir.absolutePath()) == store || !dir.cdUp()) {
214 break;
215 }
216 }
217 return {};
218}
static constexpr int kMaxNamedFields
Most named fields parse() takes from one entry.
static auto writeTemplates(const QString &storePath, const QHash< QString, QStringList > &templates) -> bool
Write templates to .templates file in password store.
static auto readTemplates(const QString &storePath) -> QHash< QString, QStringList >
Read templates from .templates file in password store.
static auto fieldsIn(const QString &templateText) -> QStringList
The field names of the template in the settings: one per line, with comment lines (starting with #,...
static auto getFolderTemplate(const QString &folderPath, const QString &storePath) -> QString
Get default template for a folder. Looks in folder, then parent folders up to root.
static auto readSecretFields(const QString &storePath) -> QStringList
The field names the store's .templates file marks as secret, in any of its sections (see secretFields...
static auto secretFieldsIn(const QString &templateText) -> QStringList
The field names a template marks as secret.
static auto openRegularFile(const QString &path, QFile &file) -> bool
Open path for reading as the regular file it is, not as what a link under that name points to: the ob...
Definition util.cpp:1529
Parser for a decrypted password entry: password line, key: value fields, remaining text and the OTP c...
TemplateIO: the store's .templates and .default_template files and the # secret: marker in template t...
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...