summaryrefslogtreecommitdiff
path: root/sal/rtl/uri.cxx
blob: 06163084893f10e8231040d08ce974123c9e8d9d (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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <rtl/character.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/textenc.h>
#include <rtl/textcvt.h>
#include <rtl/uri.h>
#include <rtl/uri.hxx>
#include <rtl/ustrbuf.h>
#include <rtl/ustrbuf.hxx>
#include <rtl/ustring.h>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <sal/macros.h>

#include <uri_internal.hxx>

#include <algorithm>
#include <cstddef>

namespace {

sal_Unicode const cEscapePrefix = 0x25; // '%'

int getHexWeight(sal_uInt32 nUtf32)
{
    return nUtf32 >= 0x30 && nUtf32 <= 0x39 ? // '0'--'9'
               static_cast< int >(nUtf32 - 0x30) :
           nUtf32 >= 0x41 && nUtf32 <= 0x46 ? // 'A'--'F'
               static_cast< int >(nUtf32 - 0x41 + 10) :
           nUtf32 >= 0x61 && nUtf32 <= 0x66 ? // 'a'--'f'
               static_cast< int >(nUtf32 - 0x61 + 10) :
               -1; // not a hex digit
}

bool isValid(sal_Bool const * pCharClass, sal_uInt32 nUtf32)
{
    return nUtf32 < rtl::UriCharClassSize && pCharClass[nUtf32];
}

void writeUnicode(rtl_uString ** pBuffer, sal_Int32 * pCapacity,
                         sal_Unicode cChar)
{
    rtl_uStringbuffer_insert(pBuffer, pCapacity, (*pBuffer)->length, &cChar, 1);
}

}

namespace rtl::uri::detail {

/** Read any of the following:

   @li sequence of escape sequences representing character from eCharset,
       translated to single UCS4 character; or
   @li pair of UTF-16 surrogates, translated to single UCS4 character; or
   @li  single UTF-16 character, extended to UCS4 character.
 */
sal_uInt32 readUcs4(sal_Unicode const ** pBegin, sal_Unicode const * pEnd,
                    bool bEncoded, rtl_TextEncoding eCharset,
                    EscapeType * pType)
{
    sal_uInt32 nChar = *(*pBegin)++;
    int nWeight1;
    int nWeight2;
    if (nChar == cEscapePrefix && bEncoded && pEnd - *pBegin >= 2
        && (nWeight1 = getHexWeight((*pBegin)[0])) >= 0
        && (nWeight2 = getHexWeight((*pBegin)[1])) >= 0)
    {
        *pBegin += 2;
        nChar = static_cast< sal_uInt32 >(nWeight1 << 4 | nWeight2);
        if (nChar <= 0x7F)
        {
            *pType = EscapeChar;
        }
        else if (eCharset == RTL_TEXTENCODING_UTF8)
        {
            if (nChar >= 0xC0 && nChar <= 0xF4)
            {
                sal_uInt32 nEncoded;
                int nShift;
                sal_uInt32 nMin;
                if (nChar <= 0xDF)
                {
                    nEncoded = (nChar & 0x1F) << 6;
                    nShift = 0;
                    nMin = 0x80;
                }
                else if (nChar <= 0xEF)
                {
                    nEncoded = (nChar & 0x0F) << 12;
                    nShift = 6;
                    nMin = 0x800;
                }
                else
                {
                    nEncoded = (nChar & 0x07) << 18;
                    nShift = 12;
                    nMin = 0x10000;
                }

                sal_Unicode const * p = *pBegin;
                bool bUTF8 = true;

                for (; nShift >= 0; nShift -= 6)
                {
                    if (pEnd - p < 3 || p[0] != cEscapePrefix
                        || (nWeight1 = getHexWeight(p[1])) < 8
                        || nWeight1 > 11
                        || (nWeight2 = getHexWeight(p[2])) < 0)
                    {
                        bUTF8 = false;
                        break;
                    }
                    p += 3;
                    nEncoded |= ((nWeight1 & 3) << 4 | nWeight2) << nShift;
                }
                if (bUTF8 && rtl::isUnicodeScalarValue(nEncoded)
                    && nEncoded >= nMin)
                {
                    *pBegin = p;
                    *pType = EscapeChar;
                    return nEncoded;
                }
            }
            *pType = EscapeOctet;
        }
        else
        {
            OStringBuffer aBuf(16);
            aBuf.append(static_cast< char >(nChar));
            rtl_TextToUnicodeConverter aConverter
                = rtl_createTextToUnicodeConverter(eCharset);
            sal_Unicode const * p = *pBegin;

            for (;;)
            {
                sal_Unicode aDst[2];
                sal_uInt32 nInfo;
                sal_Size nConverted;
                sal_Size nDstSize = rtl_convertTextToUnicode(
                    aConverter, nullptr, aBuf.getStr(), aBuf.getLength(), aDst,
                    SAL_N_ELEMENTS( aDst ),
                    (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR
                     | RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR
                     | RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR),
                    &nInfo, &nConverted);

                if (nInfo == 0)
                {
                    assert( nConverted
                        == sal::static_int_cast< sal_uInt32 >(
                            aBuf.getLength()));

                    rtl_destroyTextToUnicodeConverter(aConverter);
                    *pBegin = p;
                    *pType = EscapeChar;

                    assert( nDstSize == 1
                        || (nDstSize == 2 && rtl::isHighSurrogate(aDst[0])
                            && rtl::isLowSurrogate(aDst[1])));

                    return nDstSize == 1
                        ? aDst[0] : rtl::combineSurrogates(aDst[0], aDst[1]);
                }
                if (nInfo == RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL
                         && pEnd - p >= 3 && p[0] == cEscapePrefix
                         && (nWeight1 = getHexWeight(p[1])) >= 0
                         && (nWeight2 = getHexWeight(p[2])) >= 0)
                {
                    p += 3;
                    aBuf.append(static_cast< char >(nWeight1 << 4 | nWeight2));
                }
                else if (nInfo == RTL_TEXTTOUNICODE_INFO_SRCBUFFERTOOSMALL
                         && p != pEnd && *p <= 0x7F)
                {
                    aBuf.append(static_cast< char >(*p++));
                }
                else
                {
                    assert(
                        (nInfo & RTL_TEXTTOUNICODE_INFO_DESTBUFFERTOOSMALL)
                        == 0);
                    break;
                }
            }
            rtl_destroyTextToUnicodeConverter(aConverter);
            *pType = EscapeOctet;
        }
        return nChar;
    }

    *pType = EscapeNo;
    return rtl::isHighSurrogate(nChar) && *pBegin < pEnd
           && rtl::isLowSurrogate(**pBegin) ?
               rtl::combineSurrogates(nChar, *(*pBegin)++) : nChar;
}

}

namespace {

void writeUcs4(rtl_uString ** pBuffer, sal_Int32 * pCapacity, sal_uInt32 nUtf32)
{
    rtl_uStringbuffer_insertUtf32(pBuffer, pCapacity, (*pBuffer)->length, nUtf32);
}

void writeEscapeOctet(rtl_uString ** pBuffer, sal_Int32 * pCapacity,
                      sal_uInt32 nOctet)
{
    assert(nOctet <= 0xFF); // bad octet

    static sal_Unicode const aHex[16]
        = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
            0x41, 0x42, 0x43, 0x44, 0x45, 0x46 }; /* '0'--'9', 'A'--'F' */

    writeUnicode(pBuffer, pCapacity, cEscapePrefix);
    writeUnicode(pBuffer, pCapacity, aHex[nOctet >> 4]);
    writeUnicode(pBuffer, pCapacity, aHex[nOctet & 15]);
}

bool writeEscapeChar(rtl_uString ** pBuffer, sal_Int32 * pCapacity,
                     sal_uInt32 nUtf32, rtl_TextEncoding eCharset, bool bStrict)
{
    assert(rtl::isUnicodeCodePoint(nUtf32));
    if (eCharset == RTL_TEXTENCODING_UTF8)
    {
        if (nUtf32 < 0x80)
        {
            writeEscapeOctet(pBuffer, pCapacity, nUtf32);
        }
        else if (nUtf32 < 0x800)
        {
            writeEscapeOctet(pBuffer, pCapacity, nUtf32 >> 6 | 0xC0);
            writeEscapeOctet(pBuffer, pCapacity, (nUtf32 & 0x3F) | 0x80);
        }
        else if (nUtf32 < 0x10000)
        {
            writeEscapeOctet(pBuffer, pCapacity, nUtf32 >> 12 | 0xE0);
            writeEscapeOctet(pBuffer, pCapacity, (nUtf32 >> 6 & 0x3F) | 0x80);
            writeEscapeOctet(pBuffer, pCapacity, (nUtf32 & 0x3F) | 0x80);
        }
        else
        {
            writeEscapeOctet(pBuffer, pCapacity, nUtf32 >> 18 | 0xF0);
            writeEscapeOctet(pBuffer, pCapacity, (nUtf32 >> 12 & 0x3F) | 0x80);
            writeEscapeOctet(pBuffer, pCapacity, (nUtf32 >> 6 & 0x3F) | 0x80);
            writeEscapeOctet(pBuffer, pCapacity, (nUtf32 & 0x3F) | 0x80);
        }
    }
    else
    {
        rtl_UnicodeToTextConverter aConverter
            = rtl_createUnicodeToTextConverter(eCharset);
        sal_Unicode aSrc[2];
        sal_Size nSrcSize = rtl::splitSurrogates(nUtf32, aSrc);

        char aDst[32]; // FIXME  random value
        sal_uInt32 nInfo;
        sal_Size nConverted;
        sal_Size nDstSize = rtl_convertUnicodeToText(
            aConverter, nullptr, aSrc, nSrcSize, aDst, sizeof aDst,
            RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR
            | RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR
            | RTL_UNICODETOTEXT_FLAGS_FLUSH,
            &nInfo, &nConverted);
        assert((nInfo & RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL) == 0);
        rtl_destroyUnicodeToTextConverter(aConverter);

        if (nInfo == 0)
        {
            assert(nConverted == nSrcSize); // bad rtl_convertUnicodeToText

            for (sal_Size i = 0; i < nDstSize; ++i)
            {
                writeEscapeOctet(pBuffer, pCapacity,
                                 static_cast< unsigned char >(aDst[i]));
                    // FIXME  all octets are escaped, even if there is no need
            }
        }
        else
        {
            if (bStrict)
                return false;

            writeUcs4(pBuffer, pCapacity, nUtf32);
        }
    }
    return true;
}

struct Component
{
    sal_Unicode const * pBegin;
    sal_Unicode const * pEnd;

    Component(): pBegin(nullptr), pEnd(nullptr) {}

    bool isPresent() const { return pBegin != nullptr; }

    sal_Int32 getLength() const;
};

sal_Int32 Component::getLength() const
{
    assert(isPresent()); // taking length of non-present component
    return static_cast< sal_Int32 >(pEnd - pBegin);
}

struct Components
{
    Component aScheme;
    Component aAuthority;
    Component aPath;
    Component aQuery;
    Component aFragment;
};

void parseUriRef(rtl_uString const * pUriRef, Components * pComponents)
{
    // This algorithm is liberal and accepts various forms of illegal input.

    sal_Unicode const * pBegin = pUriRef->buffer;
    sal_Unicode const * pEnd = pBegin + pUriRef->length;
    sal_Unicode const * pPos = pBegin;

    if (pPos != pEnd && rtl::isAsciiAlpha(*pPos))
    {
        for (sal_Unicode const * p = pPos + 1; p != pEnd; ++p)
        {
            if (*p == ':')
            {
                pComponents->aScheme.pBegin = pBegin;
                pComponents->aScheme.pEnd = ++p;
                pPos = p;
                break;
            }

            if (!rtl::isAsciiAlphanumeric(*p) && *p != '+' && *p != '-'
                     && *p != '.')
            {
                break;
            }
        }
    }

    if (pEnd - pPos >= 2 && pPos[0] == '/' && pPos[1] == '/')
    {
        pComponents->aAuthority.pBegin = pPos;
        pPos += 2;
        while (pPos != pEnd && *pPos != '/' && *pPos != '?' && *pPos != '#')
        {
            ++pPos;
        }

        pComponents->aAuthority.pEnd = pPos;
    }

    pComponents->aPath.pBegin = pPos;
    while (pPos != pEnd && *pPos != '?' && * pPos != '#')
    {
        ++pPos;
    }

    pComponents->aPath.pEnd = pPos;

    if (pPos != pEnd && *pPos == '?')
    {
        pComponents->aQuery.pBegin = pPos++;
        while (pPos != pEnd && * pPos != '#')
        {
            ++pPos;
        }

        pComponents->aQuery.pEnd = pPos;
    }

    if (pPos != pEnd)
    {
        assert(*pPos == '#');
        pComponents->aFragment.pBegin = pPos;
        pComponents->aFragment.pEnd = pEnd;
    }
}

void appendPath(
    OUStringBuffer & buffer, sal_Int32 bufferStart, bool precedingSlash,
    sal_Unicode const * pathBegin, sal_Unicode const * pathEnd)
{
    while (precedingSlash || pathBegin != pathEnd)
    {
        sal_Unicode const * p = pathBegin;
        while (p != pathEnd && *p != '/')
        {
            ++p;
        }

        std::size_t n = p - pathBegin;
        if (n == 1 && pathBegin[0] == '.')
        {
            // input begins with "." -> remove from input (and done):
            //  i.e., !precedingSlash -> !precedingSlash
            // input begins with "./" -> remove from input:
            //  i.e., !precedingSlash -> !precedingSlash
            // input begins with "/." -> replace with "/" in input (and not yet
            // done):
            //  i.e., precedingSlash -> precedingSlash
            // input begins with "/./" -> replace with "/" in input:
            //  i.e., precedingSlash -> precedingSlash
        }
        else if (n == 2 && pathBegin[0] == '.' && pathBegin[1] == '.')
        {
            // input begins with ".." -> remove from input (and done):
            //  i.e., !precedingSlash -> !precedingSlash
            // input begins with "../" -> remove from input
            //  i.e., !precedingSlash -> !precedingSlash
            // input begins with "/.." -> replace with "/" in input, and shrink
            // output (not yet done):
            //  i.e., precedingSlash -> precedingSlash
            // input begins with "/../" -> replace with "/" in input, and shrink
            // output:
            //  i.e., precedingSlash -> precedingSlash
            if (precedingSlash)
            {
                buffer.truncate(
                    bufferStart
                    + std::max<sal_Int32>(
                        rtl_ustr_lastIndexOfChar_WithLength(
                            buffer.getStr() + bufferStart,
                            buffer.getLength() - bufferStart, '/'),
                        0));
            }
        }
        else
        {
            if (precedingSlash)
                buffer.append('/');

            buffer.append(pathBegin, n);
            precedingSlash = p != pathEnd;
        }
        pathBegin = p + (p == pathEnd ? 0 : 1);
    }
}

}

sal_Bool const * SAL_CALL rtl_getUriCharClass(rtl_UriCharClass eCharClass)
    SAL_THROW_EXTERN_C()
{
    static constexpr std::array<sal_Bool, rtl::UriCharClassSize> aCharClass[] = {
        rtl::createUriCharClass(u8""), // None
        rtl::createUriCharClass(
            u8"!$&'()*+,-./:;=?@[]_~"
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), // Uric
        rtl::createUriCharClass(
            u8"!$&'()*+,-.:;=?@_~"
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), // UricNoSlash
        rtl::createUriCharClass(
            u8"!$&'()*+,-.;=@_~"
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), // RelSegment
        rtl::createUriCharClass(
            u8"!$&'()*+,-.:;=@_~"
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), // RegName
        rtl::createUriCharClass(
            u8"!$&'()*+,-.:;=_~"
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), // Userinfo
        rtl::createUriCharClass(
            u8"!$&'()*+,-.:=@_~"
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), // Pchar
        rtl::createUriCharClass(
            u8"!$&'()*+-./:?@_~"
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")}; // UnoParamValue

    assert(
        (eCharClass >= 0
         && (sal::static_int_cast< std::size_t >(eCharClass)
             < SAL_N_ELEMENTS(aCharClass)))); // bad eCharClass
    return aCharClass[eCharClass].data();
}

void SAL_CALL rtl_uriEncode(rtl_uString * pText, sal_Bool const * pCharClass,
                            rtl_UriEncodeMechanism eMechanism,
                            rtl_TextEncoding eCharset, rtl_uString ** pResult)
    SAL_THROW_EXTERN_C()
{
    assert(!pCharClass[0x25]); // make sure the percent sign is encoded...

    sal_Unicode const * p = pText->buffer;
    sal_Unicode const * pEnd = p + pText->length;
    sal_Int32 nCapacity = 256;
    rtl_uString_new_WithLength(pResult, nCapacity);

    while (p < pEnd)
    {
        rtl::uri::detail::EscapeType eType;
        sal_uInt32 nUtf32 = rtl::uri::detail::readUcs4(
            &p, pEnd,
            (eMechanism == rtl_UriEncodeKeepEscapes
             || eMechanism == rtl_UriEncodeCheckEscapes
             || eMechanism == rtl_UriEncodeStrictKeepEscapes),
            eMechanism == rtl_UriEncodeStrictKeepEscapes ? RTL_TEXTENCODING_UTF8 : eCharset,
            &eType);

        switch (eType)
        {
        case rtl::uri::detail::EscapeNo:
            if (isValid(pCharClass, nUtf32)) // implies nUtf32 <= 0x7F
            {
                writeUnicode(pResult, &nCapacity,
                             static_cast< sal_Unicode >(nUtf32));
            }
            else if (!writeEscapeChar(
                         pResult, &nCapacity, nUtf32, eCharset,
                         (eMechanism == rtl_UriEncodeStrict
                          || eMechanism == rtl_UriEncodeStrictKeepEscapes)))
            {
                rtl_uString_new(pResult);
                return;
            }
            break;

        case rtl::uri::detail::EscapeChar:
            if (eMechanism == rtl_UriEncodeCheckEscapes
                && isValid(pCharClass, nUtf32)) // implies nUtf32 <= 0x7F
            {
                writeUnicode(pResult, &nCapacity,
                             static_cast< sal_Unicode >(nUtf32));
            }
            else if (!writeEscapeChar(
                         pResult, &nCapacity, nUtf32, eCharset,
                         (eMechanism == rtl_UriEncodeStrict
                          || eMechanism == rtl_UriEncodeStrictKeepEscapes)))
            {
                rtl_uString_new(pResult);
                return;
            }
            break;

        case rtl::uri::detail::EscapeOctet:
            writeEscapeOctet(pResult, &nCapacity, nUtf32);
            break;
        }
    }
    *pResult = rtl_uStringBuffer_makeStringAndClear(pResult, &nCapacity);
}

void SAL_CALL rtl_uriDecode(rtl_uString * pText,
                            rtl_UriDecodeMechanism eMechanism,
                            rtl_TextEncoding eCharset, rtl_uString ** pResult)
    SAL_THROW_EXTERN_C()
{
    switch (eMechanism)
    {
    case rtl_UriDecodeNone:
        rtl_uString_assign(pResult, pText);
        break;

    case rtl_UriDecodeToIuri:
        eCharset = RTL_TEXTENCODING_UTF8;
        [[fallthrough]];
    default: // rtl_UriDecodeWithCharset, rtl_UriDecodeStrict
        {
            sal_Unicode const * p = pText->buffer;
            sal_Unicode const * pEnd = p + pText->length;
            sal_Int32 nCapacity = pText->length;
            rtl_uString_new_WithLength(pResult, nCapacity);

            while (p < pEnd)
            {
                rtl::uri::detail::EscapeType eType;
                sal_uInt32 nUtf32 = rtl::uri::detail::readUcs4(&p, pEnd, true, eCharset, &eType);
                switch (eType)
                {
                case rtl::uri::detail::EscapeChar:
                    if (nUtf32 <= 0x7F && eMechanism == rtl_UriDecodeToIuri)
                    {
                        writeEscapeOctet(pResult, &nCapacity, nUtf32);
                        break;
                    }
                    [[fallthrough]];

                case rtl::uri::detail::EscapeNo:
                    writeUcs4(pResult, &nCapacity, nUtf32);
                    break;

                case rtl::uri::detail::EscapeOctet:
                    if (eMechanism == rtl_UriDecodeStrict)
                    {
                        rtl_uString_new(pResult);
                        return;
                    }
                    writeEscapeOctet(pResult, &nCapacity, nUtf32);
                    break;
                }
            }

            *pResult = rtl_uStringBuffer_makeStringAndClear( pResult, &nCapacity );
        }
        break;
    }
}

sal_Bool SAL_CALL rtl_uriConvertRelToAbs(rtl_uString * pBaseUriRef,
                                         rtl_uString * pRelUriRef,
                                         rtl_uString ** pResult,
                                         rtl_uString ** pException)
    SAL_THROW_EXTERN_C()
{
    // Use the strict parser algorithm from RFC 3986, section 5.2, to turn the
    // relative URI into an absolute one:
    Components aRelComponents;
    parseUriRef(pRelUriRef, &aRelComponents);
    OUStringBuffer aBuffer(256);

    if (aRelComponents.aScheme.isPresent())
    {
        aBuffer.append(aRelComponents.aScheme.pBegin,
                       aRelComponents.aScheme.getLength());

        if (aRelComponents.aAuthority.isPresent())
        {
            aBuffer.append(aRelComponents.aAuthority.pBegin,
                           aRelComponents.aAuthority.getLength());
        }

        appendPath(
            aBuffer, aBuffer.getLength(), false, aRelComponents.aPath.pBegin,
            aRelComponents.aPath.pEnd);

        if (aRelComponents.aQuery.isPresent())
        {
            aBuffer.append(aRelComponents.aQuery.pBegin,
                           aRelComponents.aQuery.getLength());
        }
    }
    else
    {
        Components aBaseComponents;
        parseUriRef(pBaseUriRef, &aBaseComponents);
        if (!aBaseComponents.aScheme.isPresent())
        {
            rtl_uString_assign(
                pException,
                (OUString(
                    "<" + OUString::unacquired(&pBaseUriRef)
                    + "> does not start with a scheme component")
                 .pData));
            return false;
        }

        aBuffer.append(aBaseComponents.aScheme.pBegin,
                       aBaseComponents.aScheme.getLength());
        if (aRelComponents.aAuthority.isPresent())
        {
            aBuffer.append(aRelComponents.aAuthority.pBegin,
                           aRelComponents.aAuthority.getLength());
            appendPath(
                aBuffer, aBuffer.getLength(), false,
                aRelComponents.aPath.pBegin, aRelComponents.aPath.pEnd);

            if (aRelComponents.aQuery.isPresent())
            {
                aBuffer.append(aRelComponents.aQuery.pBegin,
                               aRelComponents.aQuery.getLength());
            }
        }
        else
        {
            if (aBaseComponents.aAuthority.isPresent())
            {
                aBuffer.append(aBaseComponents.aAuthority.pBegin,
                               aBaseComponents.aAuthority.getLength());
            }

            if (aRelComponents.aPath.pBegin == aRelComponents.aPath.pEnd)
            {
                aBuffer.append(aBaseComponents.aPath.pBegin,
                               aBaseComponents.aPath.getLength());
                if (aRelComponents.aQuery.isPresent())
                {
                    aBuffer.append(aRelComponents.aQuery.pBegin,
                                   aRelComponents.aQuery.getLength());
                }
                else if (aBaseComponents.aQuery.isPresent())
                {
                    aBuffer.append(aBaseComponents.aQuery.pBegin,
                                   aBaseComponents.aQuery.getLength());
                }
            }
            else
            {
                if (*aRelComponents.aPath.pBegin == '/')
                {
                    appendPath(
                        aBuffer, aBuffer.getLength(), false,
                        aRelComponents.aPath.pBegin, aRelComponents.aPath.pEnd);
                }
                else if (aBaseComponents.aAuthority.isPresent()
                         && aBaseComponents.aPath.pBegin
                            == aBaseComponents.aPath.pEnd)
                {
                    appendPath(
                        aBuffer, aBuffer.getLength(), true,
                        aRelComponents.aPath.pBegin, aRelComponents.aPath.pEnd);
                }
                else
                {
                    sal_Int32 n = aBuffer.getLength();
                    sal_Int32 i = rtl_ustr_lastIndexOfChar_WithLength(
                        aBaseComponents.aPath.pBegin,
                        aBaseComponents.aPath.getLength(), '/');

                    if (i >= 0)
                    {
                        appendPath(
                            aBuffer, n, false, aBaseComponents.aPath.pBegin,
                            aBaseComponents.aPath.pBegin + i);
                    }

                    appendPath(
                        aBuffer, n, i >= 0, aRelComponents.aPath.pBegin,
                        aRelComponents.aPath.pEnd);
                }

                if (aRelComponents.aQuery.isPresent())
                {
                    aBuffer.append(aRelComponents.aQuery.pBegin,
                                   aRelComponents.aQuery.getLength());
                }
            }
        }
    }
    if (aRelComponents.aFragment.isPresent())
    {
        aBuffer.append(aRelComponents.aFragment.pBegin,
                       aRelComponents.aFragment.getLength());
    }

    rtl_uString_assign(pResult, aBuffer.makeStringAndClear().pData);
    return true;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */