summaryrefslogtreecommitdiff
path: root/poppler/DistinguishedNameParser.h
blob: dfabc97e07d615cab971ce49f28ba3a1501bdc77 (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
//========================================================================
//
// DistinguishedNameParser.h
//
// This file is licensed under the GPLv2 or later
//
// Copyright 2002 g10 Code GmbH
// Copyright 2004 Klarälvdalens Datakonsult AB
// Copyright 2021 g10 Code GmbH
// Copyright 2023 g10 Code GmbH, Author: Sune Stolborg Vuorela <sune@vuorela.dk>
//
// Derived from libkleopatra (KDE key management library) dn.cpp
//
//========================================================================

#ifndef DISTINGUISHEDNAMEPARSER_H
#define DISTINGUISHEDNAMEPARSER_H

#include <vector>
#include <string>
#include <utility>
#include <optional>
#include <algorithm>

namespace DN {
namespace detail {

inline std::string_view removeLeadingSpaces(std::string_view view)
{
    auto pos = view.find_first_not_of(' ');
    if (pos > view.size()) {
        return {};
    }
    return view.substr(pos);
}

inline std::string_view removeTrailingSpaces(std::string_view view)
{
    auto pos = view.find_last_not_of(' ');
    if (pos > view.size()) {
        return {};
    }
    return view.substr(0, pos + 1);
}

inline unsigned char xtoi(unsigned char c)
{
    if (c <= '9') {
        return c - '0';
    }
    if (c <= 'F') {
        return c - 'A' + 10;
    }
    return c < 'a' + 10;
}

inline unsigned char xtoi(unsigned char first, unsigned char second)
{
    return 16 * xtoi(first) + xtoi(second);
}
// Parses a hex string into actual content
inline std::optional<std::string> parseHexString(std::string_view view)
{
    auto size = view.size();
    if (size == 0 || (size % 2 == 1)) {
        return std::nullopt;
    }
    // It is only supposed to be called with actual hex strings
    // but this is just to be extra sure
    auto endHex = view.find_first_not_of("1234567890abcdefABCDEF");
    if (endHex != std::string_view::npos) {
        return {};
    }
    std::string result;
    result.reserve(size / 2);
    for (size_t i = 0; i < (view.size() - 1); i += 2) {
        result.push_back(xtoi(view[i], view[i + 1]));
    }
    return result;
}

static const std::vector<std::pair<std::string_view, std::string_view>> oidmap = {
    // clang-format off
    // keep them ordered by oid:
    {"NameDistinguisher", "0.2.262.1.10.7.20"   },
    {"EMAIL",             "1.2.840.113549.1.9.1"},
    {"CN",                "2.5.4.3"             },
    {"SN",                "2.5.4.4"             },
    {"SerialNumber",      "2.5.4.5"             },
    {"T",                 "2.5.4.12"            },
    {"D",                 "2.5.4.13"            },
    {"BC",                "2.5.4.15"            },
    {"ADDR",              "2.5.4.16"            },
    {"PC",                "2.5.4.17"            },
    {"GN",                "2.5.4.42"            },
    {"Pseudo",            "2.5.4.65"            },
    // clang-format on
};

static std::string_view attributeNameForOID(std::string_view oid)
{
    if (oid.substr(0, 4) == std::string_view { "OID." } || oid.substr(0, 4) == std::string_view { "oid." }) { // c++20 has starts_with. we don't have that yet.
        oid.remove_prefix(4);
    }
    for (const auto &m : oidmap) {
        if (oid == m.second) {
            return m.first;
        }
    }
    return {};
}

/* Parse a DN and return an array-ized one.  This is not a validating
   parser and it does not support any old-stylish syntax; gpgme is
   expected to return only rfc2253 compatible strings. */
static std::pair<std::optional<std::string_view>, std::pair<std::string, std::string>> parse_dn_part(std::string_view stringv)
{
    std::pair<std::string, std::string> dnPair;
    auto separatorPos = stringv.find_first_of('=');
    if (separatorPos == 0 || separatorPos == std::string_view::npos) {
        return {}; /* empty key */
    }

    std::string_view key = stringv.substr(0, separatorPos);
    key = removeTrailingSpaces(key);
    // map OIDs to their names:
    if (auto name = attributeNameForOID(key); !name.empty()) {
        key = name;
    }

    dnPair.first = std::string { key };
    stringv = removeLeadingSpaces(stringv.substr(separatorPos + 1));
    if (stringv.empty()) {
        return {};
    }

    if (stringv.front() == '#') {
        /* hexstring */
        stringv.remove_prefix(1);
        auto endHex = stringv.find_first_not_of("1234567890abcdefABCDEF");
        if (!endHex || (endHex % 2 == 1)) {
            return {}; /* empty or odd number of digits */
        }
        auto value = parseHexString(stringv.substr(0, endHex));
        if (!value.has_value()) {
            return {};
        }
        stringv = stringv.substr(endHex);
        dnPair.second = value.value();
    } else if (stringv.front() == '"') {
        stringv.remove_prefix(1);
        std::string value;
        bool stop = false;
        while (!stringv.empty() && !stop) {
            switch (stringv.front()) {
            case '\\': {
                if (stringv.size() < 2) {
                    return {};
                }
                if (stringv[1] == '"') {
                    value.push_back('"');
                    stringv.remove_prefix(2);
                } else {
                    // it is a bit unclear in rfc2253 if escaped hex chars should
                    // be decoded inside quotes. Let's just forward the verbatim
                    // for now
                    value.push_back(stringv.front());
                    value.push_back(stringv[1]);
                    stringv.remove_prefix(2);
                }
                break;
            }
            case '"': {
                stop = true;
                stringv.remove_prefix(1);
                break;
            }
            default: {
                value.push_back(stringv.front());
                stringv.remove_prefix(1);
            }
            }
        }
        if (!stop) {
            // we have reached end of string, but never an actual ", so error out
            return {};
        }
        dnPair.second = value;
    } else {
        std::string value;
        bool stop = false;
        bool lastAddedEscapedSpace = false;
        while (!stringv.empty() && !stop) {
            switch (stringv.front()) {
            case '\\': //_escaping
            {
                stringv.remove_prefix(1);
                if (stringv.empty()) {
                    return {};
                }
                switch (stringv.front()) {
                case ',':
                case '=':
                case '+':
                case '<':
                case '>':
                case '#':
                case ';':
                case '\\':
                case '"':
                case ' ': {
                    if (stringv.front() == ' ') {
                        lastAddedEscapedSpace = true;
                    } else {
                        lastAddedEscapedSpace = false;
                    }
                    value.push_back(stringv.front());
                    stringv.remove_prefix(1);
                    break;
                }
                default: {
                    if (stringv.size() < 2) {
                        // this should be double hex-ish, but isn't.
                        return {};
                    }
                    if (std::isxdigit(stringv.front()) && std::isxdigit(stringv[1])) {
                        lastAddedEscapedSpace = false;
                        value.push_back(xtoi(stringv.front(), stringv[1]));
                        stringv.remove_prefix(2);
                        break;
                    } else {
                        // invalid escape
                        return {};
                    }
                }
                }
                break;
            }
            case '"':
                // unescaped " in the middle; not allowed
                return {};
            case ',':
            case '=':
            case '+':
            case '<':
            case '>':
            case '#':
            case ';': {
                stop = true;
                break; //
            }
            default:
                lastAddedEscapedSpace = false;
                value.push_back(stringv.front());
                stringv.remove_prefix(1);
            }
        }
        if (lastAddedEscapedSpace) {
            dnPair.second = value;
        } else {
            dnPair.second = std::string { removeTrailingSpaces(value) };
        }
    }
    return { stringv, dnPair };
}
}

using Result = std::vector<std::pair<std::string, std::string>>;

/* Parse a DN and return an array-ized one.  This is not a validating
   parser and it does not support any old-stylish syntax; gpgme is
   expected to return only rfc2253 compatible strings. */
static Result parseString(std::string_view string)
{
    Result result;
    while (!string.empty()) {
        string = detail::removeLeadingSpaces(string);
        if (string.empty()) {
            break;
        }

        auto [partResult, dnPair] = detail::parse_dn_part(string);
        if (!partResult.has_value()) {
            return {};
        }

        string = partResult.value();
        if (dnPair.first.size() && dnPair.second.size()) {
            result.emplace_back(std::move(dnPair));
        }

        string = detail::removeLeadingSpaces(string);
        if (string.empty()) {
            break;
        }
        switch (string.front()) {
        case ',':
        case ';':
        case '+':
            string.remove_prefix(1);
            break;
        default:
            // some unexpected characters here
            return {};
        }
    }
    return result;
}

/// returns the first value of a given key (note. there can be multiple)
/// or nullopt if key is not available
inline std::optional<std::string> FindFirstValue(const Result &dn, std::string_view key)
{
    auto first = std::find_if(dn.begin(), dn.end(), [&key](const auto &it) { return it.first == key; });
    if (first == dn.end()) {
        return {};
    }
    return first->second;
}
} // namespace DN
#endif // DISTINGUISHEDNAMEPARSER_H