summaryrefslogtreecommitdiffstats
path: root/src/dom/uri.cpp
blob: e68caf898a375b48b477e673e71d658648b19e75 (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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
/**
 * Phoebe DOM Implementation.
 *
 * This is a C++ approximation of the W3C DOM model, which follows
 * fairly closely the specifications in the various .idl files, copies of
 * which are provided for reference.  Most important is this one:
 *
 * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html
 *
 * Authors:
 *   Bob Jamison
 *
 * Copyright (C) 2005-2007 Bob Jamison
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */




#include "uri.h"
#include "charclass.h"

#include <stdio.h>
#include <stdarg.h>
#include <vector>


namespace org
{
namespace w3c
{
namespace dom
{


typedef struct
{
    int  ival;
    char const *sval;
    int  port;
} LookupEntry;

static LookupEntry schemes[] =
{
    { URI::SCHEME_DATA,   "data:",    0 },
    { URI::SCHEME_HTTP,   "http:",   80 },
    { URI::SCHEME_HTTPS,  "https:", 443 },
    { URI::SCHEME_FTP,    "ftp",     12 },
    { URI::SCHEME_FILE,   "file:",    0 },
    { URI::SCHEME_LDAP,   "ldap:",  123 },
    { URI::SCHEME_MAILTO, "mailto:", 25 },
    { URI::SCHEME_NEWS,   "news:",  117 },
    { URI::SCHEME_TELNET, "telnet:", 23 },
    { 0,                  NULL,       0 }
};



//#########################################################################
//# C O N S T R U C T O R
//#########################################################################

/**
 *
 */
URI::URI()
{
    init();
}

/**
 *
 */
URI::URI(const DOMString &str)
{
    init();
    parse(str);
}


/**
 *
 */
URI::URI(const char *str)
{
    init();
    DOMString domStr = str;
    parse(domStr);
}


/**
 *
 */
URI::URI(const URI &other)
{
    init();
    assign(other);
}


/**
 *
 */
URI &URI::operator=(const URI &other)
{
    init();
    assign(other);
    return *this;
}


/**
 *
 */
URI::~URI()
{
}





/**
 *
 */
void URI::init()
{
    parsebuf  = NULL;
    parselen  = 0;
    scheme    = SCHEME_NONE;
    schemeStr.clear();
    port      = 0;
    authority.clear();
    path.clear();
    absolute  = false;
    opaque    = false;
    query.clear();
    fragment.clear();
}


/**
 *
 */
void URI::assign(const URI &other)
{
    scheme    = other.scheme;
    schemeStr = other.schemeStr;
    authority = other.authority;
    port      = other.port;
    path      = other.path;
    absolute  = other.absolute;
    opaque    = other.opaque;
    query     = other.query;
    fragment  = other.fragment;
}


//#########################################################################
//#A T T R I B U T E S
//#########################################################################
static char *hexChars = "0123456789abcdef";

static DOMString toStr(const std::vector<int> &arr)
{
    DOMString buf;
    std::vector<int>::const_iterator iter;
    for (iter=arr.begin() ; iter!=arr.end() ; iter++)
        {
        int ch = *iter;
        if (isprint(ch))
            buf.push_back((XMLCh)ch);
        else
            {
            buf.push_back('%');
            int hi = ((ch>>4) & 0xf);
            buf.push_back(hexChars[hi]);
            int lo = ((ch   ) & 0xf);
            buf.push_back(hexChars[lo]);
            }
        }
    return buf;
}


DOMString URI::toString() const
{
    DOMString str = schemeStr;
    if (authority.size() > 0)
        {
        str.append("//");
        str.append(toStr(authority));
        }
    str.append(toStr(path));
    if (query.size() > 0)
        {
        str.append("?");
        str.append(toStr(query));
        }
    if (fragment.size() > 0)
        {
        str.append("#");
        str.append(toStr(fragment));
        }
    return str;
}


int URI::getScheme() const
{
    return scheme;
}

DOMString URI::getSchemeStr() const
{
    return schemeStr;
}


DOMString URI::getAuthority() const
{
    DOMString ret = toStr(authority);
    if (portSpecified && port>=0)
        {
        char buf[7];
        snprintf(buf, 6, ":%6d", port);
        ret.append(buf);
        }
    return ret;
}

DOMString URI::getHost() const
{
    DOMString str = toStr(authority);
    return str;
}

int URI::getPort() const
{
    return port;
}


DOMString URI::getPath() const
{
    DOMString str = toStr(path);
    return str;
}

DOMString URI::getNativePath() const
{
    DOMString pathStr = toStr(path);
    DOMString npath;
#ifdef __WIN32__
    unsigned int firstChar = 0;
    if (pathStr.size() >= 3)
        {
        if (pathStr[0] == '/' &&
            isLetter(pathStr[1]) &&
            pathStr[2] == ':')
            firstChar++;
         }
    for (unsigned int i=firstChar ; i<pathStr.size() ; i++)
        {
        XMLCh ch = (XMLCh) pathStr[i];
        if (ch == '/')
            npath.push_back((XMLCh)'\\');
        else
            npath.push_back(ch);
        }
#else
    npath = pathStr;
#endif
    return npath;
}


bool URI::isAbsolute() const
{
    return absolute;
}

bool URI::isOpaque() const
{
    return opaque;
}


DOMString URI::getQuery() const
{
    DOMString str = toStr(query);
    return str;
}


DOMString URI::getFragment() const
{
    DOMString str = toStr(fragment);
    return str;
}




static int find(const std::vector<int> &str, int ch, int startpos)
{
    for (unsigned int i = startpos ; i < str.size() ; i++)
        {
        if (ch == str[i])
            return i;
        }
    return -1;
}


static int findLast(const std::vector<int> &str, int ch)
{
    for (unsigned int i = str.size()-1 ; i>=0 ; i--)
        {
        if (ch == str[i])
            return i;
        }
    return -1;
}


static bool sequ(const std::vector<int> &str, char *key)
{
    char *c = key;
    for (unsigned int i=0 ; i<str.size() ; i++)
        {
        if (! (*c))
            return false;
        if (*c != str[i])
            return false;
        }
    return true;
}


static std::vector<int> substr(const std::vector<int> &str,
                      int startpos, int len)
{
    std::vector<int> buf;
    unsigned int pos = startpos;
    for (int i=0 ; i<len ; i++)
        {
        if (pos >= str.size())
            break;
        buf.push_back(str[pos++]);
        }
    return buf;
}


URI URI::resolve(const URI &other) const
{
    //### According to w3c, this is handled in 3 cases

    //## 1
    if (opaque || other.isAbsolute())
        return other;

    //## 2
    if (other.fragment.size()  >  0 &&
        other.path.size()      == 0 &&
        other.scheme           == SCHEME_NONE &&
        other.authority.size() == 0 &&
        other.query.size()     == 0 )
        {
        URI fragUri = *this;
        fragUri.fragment = other.fragment;
        return fragUri;
        }

    //## 3 http://www.ietf.org/rfc/rfc2396.txt, section 5.2
    URI newUri;
    //# 3.1
    newUri.scheme    = scheme;
    newUri.schemeStr = schemeStr;
    newUri.query     = other.query;
    newUri.fragment  = other.fragment;
    if (other.authority.size() > 0)
        {
        //# 3.2
        if (absolute || other.absolute)
            newUri.absolute = true;
        newUri.authority = other.authority;
        newUri.port      = other.port;//part of authority
        newUri.path      = other.path;
        }
    else
        {
        //# 3.3
        if (other.absolute)
            {
            newUri.absolute = true;
            newUri.path     = other.path;
            }
        else
            {
            int pos = findLast(path, '/');
            if (pos >= 0)
                {
                newUri.path.clear();
                //# append my path up to and including the '/'
                for (int i = 0; i<=pos ; i++)
                       newUri.path.push_back(path[i]);
                //# append other path
                for (unsigned int i = 0; i<other.path.size() ; i++)
                       newUri.path.push_back(other.path[i]);
                }
            else
                newUri.path = other.path;
            }
        }

    newUri.normalize();

    return newUri;
}


/**
 *  This follows the Java URI algorithm:
 *   1. All "." segments are removed.
 *   2. If a ".." segment is preceded by a non-".." segment
 *          then both of these segments are removed. This step
 *          is repeated until it is no longer applicable.
 *   3. If the path is relative, and if its first segment
 *          contains a colon character (':'), then a "." segment
 *          is prepended. This prevents a relative URI with a path
 *          such as "a:b/c/d" from later being re-parsed as an
 *          opaque URI with a scheme of "a" and a scheme-specific
 *          part of "b/c/d". (Deviation from RFC 2396)
 */
void URI::normalize()
{
    std::vector< std::vector<int> > segments;

    //## Collect segments
    if (path.size()<2)
        return;
    bool abs = false;
    int pos=0;
    int len = (int) path.size();

    if (path[0]=='/')
        {
        abs = true;
        pos++;
        }

    while (pos < len)
        {
        int pos2 = find(path, '/', pos);
        if (pos2 < 0)
            {
            std::vector<int> seg = substr(path, pos, path.size()-pos);
            //printf("last segment:%s\n", toStr(seg).c_str());
            segments.push_back(seg);
            break;
            }
        if (pos2>pos)
            {
            std::vector<int> seg = substr(path, pos, pos2-pos);
            //printf("segment:%s\n", toStr(seg).c_str());
            segments.push_back(seg);
            }
        pos = pos2;
        pos++;
        }

    //## Clean up (normalize) segments
    bool edited = false;
    std::vector< std::vector<int> >::iterator iter;
    for (iter=segments.begin() ; iter!=segments.end() ; )
        {
        std::vector<int> s = *iter;
        if (sequ(s,"."))
            {
            iter = segments.erase(iter);
            edited = true;
            }
        else if (sequ(s, "..") && iter != segments.begin() &&
                 !sequ(*(iter-1), ".."))
            {
            iter--; //back up, then erase two entries
            iter = segments.erase(iter);
            iter = segments.erase(iter);
            edited = true;
            }
        else
            iter++;
        }

    //## Rebuild path, if necessary
    if (edited)
        {
        path.clear();
        if (abs)
            {
            path.push_back('/');
            }
        std::vector< std::vector<int> >::iterator iter;
        for (iter=segments.begin() ; iter!=segments.end() ; iter++)
            {
            if (iter != segments.begin())
                path.push_back('/');
            std::vector<int> seg = *iter;
            for (unsigned int i = 0; i<seg.size() ; i++)
                path.push_back(seg[i]);
            }
        }

}



//#########################################################################
//# M E S S A G E S
//#########################################################################

void URI::error(const char *fmt, ...)
{
    va_list args;
    fprintf(stderr, "URI error: ");
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
    fprintf(stderr, "\n");
}

void URI::trace(const char *fmt, ...)
{
    va_list args;
    fprintf(stdout, "URI: ");
    va_start(args, fmt);
    vfprintf(stdout, fmt, args);
    va_end(args);
    fprintf(stdout, "\n");
}



//#########################################################################
//# P A R S I N G
//#########################################################################



int URI::peek(int p)
{
    if (p<0 || p>=parselen)
        return -1;
    return parsebuf[p];
}



int URI::match(int p0, char const *key)
{
    int p = p0;
    while (p < parselen)
        {
        if (*key == '\0')
            return p;
        else if (*key != parsebuf[p])
            break;
        p++; key++;
        }
    return p0;
}

//#########################################################################
//#  Parsing is performed according to:
//#  http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#components
//#########################################################################

int URI::parseHex(int p0, int &result)
{
    int p = p0;
    int val = 0;

    //# Upper 4
    int ch = peek(p);
    if (ch >= '0' && ch <= '9')
        val += (ch - '0');
    else if (ch >= 'a' && ch <= 'f')
        val += (10 + ch - 'a');
    else if (ch >= 'A' && ch <= 'F')
        val += (10 + ch - 'A');
    else
        {
        error("parseHex : unexpected character : %c", ch);
        return -1;
        }
    p++;
    val <<= 4;

    //# Lower 4
    ch = peek(p);
    if (ch >= '0' && ch <= '9')
        val += (ch - '0');
    else if (ch >= 'a' && ch <= 'f')
        val += (10 + ch - 'a');
    else if (ch >= 'A' && ch <= 'F')
        val += (10 + ch - 'A');
    else
        {
        error("parseHex : unexpected character : %c", ch);
        return -1;
        }
    p++;
    result = val;
    return p;
}



int URI::parseEntity(int p0, int &result)
{
    int p = p0;
    int ch = peek(p);
    if (ch != '&')
        return p0;
    p++;
    if (!match(p, "#x"))
        {
        error("parseEntity: expected '#x'");
        return -1;
        }
    p += 2;
    int val;
    p = parseHex(p, val);
    if (p<0)
        return -1;
    ch = peek(p);
    if (ch != ';')
        {
        error("parseEntity: expected ';'");
        return -1;
        }
    p++;
    result = val;
    return p;
}

int URI::parseAsciiEntity(int p0, int &result)
{
    int p = p0;
    int ch = peek(p);
    if (ch != '%')
        return p0;
    p++;
    int val;
    p = parseHex(p, val);
    if (p<0)
        return -1;
    result = val;
    return p;
}


int URI::parseScheme(int p0)
{
    int p = p0;
    for (LookupEntry *entry = schemes; entry->sval ; entry++)
        {
        int p2 = match(p, entry->sval);
        if (p2 > p)
            {
            schemeStr = entry->sval;
            scheme    = entry->ival;
            port      = entry->port;
            p = p2;
            return p;
            }
        }

    return p;
}


int URI::parseHierarchicalPart(int p0)
{
    int p = p0;
    int ch;

    //# Authority field (host and port, for example)
    int p2 = match(p, "//");
    if (p2 > p)
        {
        p = p2;
        portSpecified = false;
        DOMString portStr;
        while (p < parselen)
            {
            ch = peek(p);
            if (ch == '/')
                break;
            else if (ch == '&') //IRI entity
                {
                int val;
                p2 = parseEntity(p, val);
                if (p2<p)
                    {
                    return -1;
                    }
                p = p2;
                authority.push_back((XMLCh)val);
                }
            else if (ch == '%') //ascii hex excape
                {
                int val;
                p2 = parseAsciiEntity(p, val);
                if (p2<p)
                    {
                    return -1;
                    }
                p = p2;
                authority.push_back((XMLCh)val);
                }
            else if (ch == ':')
                {
                portSpecified = true;
                p++;
                }
            else if (portSpecified)
                {
                portStr.push_back((XMLCh)ch);
                p++;
                }
            else
                {
                authority.push_back((XMLCh)ch);
                p++;
                }
            }
        if (portStr.size() > 0)
            {
            char *pstr = (char *)portStr.c_str();
            char *endStr;
            long val = strtol(pstr, &endStr, 10);
            if (endStr > pstr) //successful parse?
                port = val;
            }
        }

    //# Are we absolute?
    ch = peek(p);
    if (isLetter(ch) && peek(p+1)==':')
        {
        absolute = true;
        path.push_back((XMLCh)'/');
        }
    else if (ch == '/')
        {
        absolute = true;
        if (p>p0) //in other words, if '/' is not the first char
            opaque = true;
        path.push_back((XMLCh)ch);
        p++;
        }

    while (p < parselen)
        {
        ch = peek(p);
        if (ch == '?' || ch == '#')
            break;
        else if (ch == '&') //IRI entity
            {
            int val;
            p2 = parseEntity(p, val);
            if (p2<p)
                {
                return -1;
                }
            p = p2;
            path.push_back((XMLCh)val);
            }
        else if (ch == '%') //ascii hex excape
            {
            int val;
            p2 = parseAsciiEntity(p, val);
            if (p2<p)
                {
                return -1;
                }
            p = p2;
            path.push_back((XMLCh)val);
            }
        else
            {
            path.push_back((XMLCh)ch);
            p++;
            }
        }
    //trace("path:%s", toStr(path).c_str());
    return p;
}

int URI::parseQuery(int p0)
{
    int p = p0;
    int ch = peek(p);
    if (ch != '?')
        return p0;

    p++;
    while (p < parselen)
        {
        ch = peek(p);
        if (ch == '#')
            break;
        query.push_back((XMLCh)ch);
        p++;
        }


    return p;
}

int URI::parseFragment(int p0)
{

    int p = p0;
    int ch = peek(p);
    if (ch != '#')
        return p0;

    p++;
    while (p < parselen)
        {
        ch = peek(p);
        if (ch == '?')
            break;
        fragment.push_back(ch);
        p++;
        }


    return p;
}


int URI::parse(int p0)
{

    int p = p0;

    int p2 = parseScheme(p);
    if (p2 < 0)
        {
        error("Scheme");
        return -1;
        }
    p = p2;


    p2 = parseHierarchicalPart(p);
    if (p2 < 0)
        {
        error("Hierarchical part");
        return -1;
        }
    p = p2;

    p2 = parseQuery(p);
    if (p2 < 0)
        {
        error("Query");
        return -1;
        }
    p = p2;


    p2 = parseFragment(p);
    if (p2 < 0)
        {
        error("Fragment");
        return -1;
        }
    p = p2;

    return p;

}



bool URI::parse(const DOMString &str)
{

    parselen = str.size();
    parsebuf = new int[str.size()];
    if (!parsebuf)
        {
        error("parse : could not allocate parsebuf");
        return false;
        }

    DOMString::const_iterator iter;
    unsigned int i=0;
    for (iter= str.begin() ; iter!=str.end() ; iter++)
        {
        int ch = *iter;
        if (ch == '\\')
            parsebuf[i++] = '/';
        else
            parsebuf[i++] = ch;
        }


    int p = parse(0);
    normalize();

    delete[] parsebuf;

    if (p < 0)
        {
        error("Syntax error");
        return false;
        }

    //printf("uri:%s\n", toString().c_str());
    //printf("parse:%s\n", toStr(path).c_str());

    return true;

}





}  //namespace dom
}  //namespace w3c
}  //namespace org
//#########################################################################
//# E N D    O F    F I L E
//#########################################################################