aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/string_utils/quote/quote.cpp
blob: a445636fd63f047c4c8af0853602095d076772fb (plain) (blame)
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
#include "quote.h"

#include <util/memory/tempbuf.h>
#include <util/string/ascii.h>
#include <util/string/cstriter.h>

#include <cctype>

/* note: (x & 0xdf) makes x upper case */
#define GETXC                                                           \
    do {                                                                \
        c *= 16;                                                        \
        c += (x[0] >= 'A' ? ((x[0] & 0xdf) - 'A') + 10 : (x[0] - '0')); \
        ++x;                                                            \
    } while (0)

#define GETSBXC                                                         \
    do {                                                                \
        c *= 16;                                                        \
        c += (x[0] >= 'A' ? ((x[0] & 0xdf) - 'A') + 10 : (x[0] - '0')); \
        x.Skip(1);                                                      \
    } while (0)


namespace {
    class TFromHexZeroTerm {
    public:
        static inline char x2c(const char*& x) {
            if (!IsAsciiHex((ui8)x[0]) || !IsAsciiHex((ui8)x[1]))
                return '%';
            ui8 c = 0;

            GETXC;
            GETXC;
            return c;
        }

        static inline char x2c(TStringBuf& x) {
            if (!IsAsciiHex((ui8)x[0]) || !IsAsciiHex((ui8)x[1]))
                return '%';
            ui8 c = 0;

            GETSBXC;
            GETSBXC;
            return c;
        }
    };

    class TFromHexLenLimited {
    public:
        TFromHexLenLimited(const char* end)
            : End(end)
        {
        }

        inline char x2c(const char*& x) {
            if (x + 2 > End)
                return '%';
            return TFromHexZeroTerm::x2c(x);
        }

    private:
        const char* End;
    };
}

static inline char d2x(unsigned x) {
    return (char)((x < 10) ? ('0' + x) : ('A' + x - 10));
}

static inline const char* FixZero(const char* s) noexcept {
    return s ? s : "";
}

// we escape:
// '\"', '|', '(', ')',
// '%',  '&', '+', ',',
// '#',  '<', '=', '>',
// '[',  '\\',']', '?',
//  ':', '{', '}', 
// all below ' ' (0x20) and above '~' (0x7E).
// ' ' converted to '+' 
static const bool chars_to_url_escape[256] = {
    //  0  1  2  3   4  5  6  7   8  9  A  B   C  D  E  F
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //0
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //1
    0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, //2
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, //3

    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //4
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, //5
    1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //6
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, //7

    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //8
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //9
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //A
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //B

    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //C
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //D
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //E
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //F
};

template <class It1, class It2, class It3>
static inline It1 Escape(It1 to, It2 from, It3 end, const bool* escape_map = chars_to_url_escape) {
    while (from != end) {
        if (escape_map[(unsigned char)*from]) {
            *to++ = '%';
            *to++ = d2x((unsigned char)*from >> 4);
            *to++ = d2x((unsigned char)*from & 0xF);
        } else {
            *to++ = (*from == ' ' ? '+' : *from); 
        }

        ++from;
    }

    *to = 0;

    return to;
}

template <class It1, class It2, class It3, class FromHex>
static inline It1 Unescape(It1 to, It2 from, It3 end, FromHex fromHex) { 
    (void)fromHex;

    while (from != end) {
        switch (*from) {
            case '%':
                ++from;
                *to++ = fromHex.x2c(from);
                break;
            case '+':
                *to++ = ' ';
                ++from;
                break;
            default:
                *to++ = *from++;
        }
    }
    *to = 0;
    return to;
}

// CGIEscape returns pointer to the end of the result string
// so as it could be possible to populate single long buffer
// with several calls to CGIEscape in a row.
char* CGIEscape(char* to, const char* from) {
    return Escape(to, FixZero(from), TCStringEndIterator());
}

char* CGIEscape(char* to, const char* from, size_t len) {
    return Escape(to, from, from + len);
}

void CGIEscape(TString& url) {
    TTempBuf tempBuf(CgiEscapeBufLen(url.size()));
    char* to = tempBuf.Data();

    url.AssignNoAlias(to, CGIEscape(to, url.data(), url.size()));
}

TString CGIEscapeRet(const TStringBuf url) {
    TString to;
    to.ReserveAndResize(CgiEscapeBufLen(url.size()));
    to.resize(CGIEscape(to.begin(), url.data(), url.size()) - to.data());
    return to;
} 
 
TString& AppendCgiEscaped(const TStringBuf value, TString& to) {
    const size_t origLength = to.length();
    to.ReserveAndResize(origLength + CgiEscapeBufLen(value.size()));
    to.resize(CGIEscape(to.begin() + origLength, value.data(), value.size()) - to.data());
    return to;
}

// More general version of CGIEscape. The optional safe parameter specifies
// additional characters that should not be quoted — its default value is '/'.

// Also returns pointer to the end of result string.

template <class It1, class It2, class It3>
static inline It1 Quote(It1 to, It2 from, It3 end, const char* safe) {
    bool escape_map[256];
    memcpy(escape_map, chars_to_url_escape, 256);
    // RFC 3986 Uniform Resource Identifiers (URI): Generic Syntax
    // lists following reserved characters:
    const char* reserved = ":/?#[]@!$&\'()*+,;=";
    for (const char* p = reserved; *p; ++p) {
        escape_map[(unsigned char)*p] = 1;
    }
    // characters we think are safe at the moment
    for (const char* p = safe; *p; ++p) {
        escape_map[(unsigned char)*p] = 0;
    }

    return Escape(to, from, end, escape_map);
}

char* Quote(char* to, const char* from, const char* safe) {
    return Quote(to, FixZero(from), TCStringEndIterator(), safe);
}

char* Quote(char* to, const TStringBuf s, const char* safe) {
    return Quote(to, s.data(), s.data() + s.size(), safe);
}

void Quote(TString& url, const char* safe) {
    TTempBuf tempBuf(CgiEscapeBufLen(url.size()));
    char* to = tempBuf.Data();

    url.AssignNoAlias(to, Quote(to, url, safe));
}

char* CGIUnescape(char* to, const char* from) {
    return Unescape(to, FixZero(from), TCStringEndIterator(), TFromHexZeroTerm()); 
}

char* CGIUnescape(char* to, const char* from, size_t len) { 
    return Unescape(to, from, from + len, TFromHexLenLimited(from + len)); 
}

void CGIUnescape(TString& url) {
    if (url.empty()) {
        return;
    }
    if (url.IsDetached()) { // in-place when refcount == 1
        char* resBegin = url.begin();
        const char* resEnd = CGIUnescape(resBegin, resBegin, url.size());
        url.resize(resEnd - resBegin);
    } else {
        url = CGIUnescapeRet(url);
    }
}

TString CGIUnescapeRet(const TStringBuf from) {
    TString to;
    to.ReserveAndResize(CgiUnescapeBufLen(from.size()));
    to.resize(CGIUnescape(to.begin(), from.data(), from.size()) - to.data());
    return to;
} 
 
char* UrlUnescape(char* to, TStringBuf from) {
    while (!from.empty()) {
        char ch = from[0];
        from.Skip(1);
        if ('%' == ch && 2 <= from.length())
            ch = TFromHexZeroTerm::x2c(from);
        *to++ = ch;
    }

    *to = 0;

    return to;
}

void UrlUnescape(TString& url) {
    if (url.empty()) {
        return;
    }
    if (url.IsDetached()) { // in-place when refcount == 1
        char* resBegin = url.begin();
        const char* resEnd = UrlUnescape(resBegin, url);
        url.resize(resEnd - resBegin);
    } else {
        url = UrlUnescapeRet(url);
    }
}

TString UrlUnescapeRet(const TStringBuf from) {
    TString to;
    to.ReserveAndResize(CgiUnescapeBufLen(from.size()));
    to.resize(UrlUnescape(to.begin(), from) - to.data());
    return to;
}

char* UrlEscape(char* to, const char* from, bool forceEscape) {
    from = FixZero(from);

    while (*from) {
        const bool escapePercent = (*from == '%') &&
                                   (forceEscape || !((*(from + 1) && IsAsciiHex(*(from + 1)) && *(from + 2) && IsAsciiHex(*(from + 2)))));

        if (escapePercent || (unsigned char)*from <= ' ' || (unsigned char)*from > '~') {
            *to++ = '%';
            *to++ = d2x((unsigned char)*from >> 4);
            *to++ = d2x((unsigned char)*from & 0xF);
        } else
            *to++ = *from;
        ++from;
    }

    *to = 0;

    return to;
}

void UrlEscape(TString& url, bool forceEscape) {
    TTempBuf tempBuf(CgiEscapeBufLen(url.size()));
    char* to = tempBuf.Data();
    url.AssignNoAlias(to, UrlEscape(to, url.data(), forceEscape));
}

TString UrlEscapeRet(const TStringBuf from, bool forceEscape) {
    TString to;
    to.ReserveAndResize(CgiEscapeBufLen(from.size()));
    to.resize(UrlEscape(to.begin(), from.begin(), forceEscape) - to.data());
    return to;
}