summaryrefslogtreecommitdiffstats
path: root/src/object/uri.cpp
blob: 05539a69e258c711e9c52abab57104151831e2e2 (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
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Authors:
 *   MenTaLguY <mental@rydia.net>
 *   Jon A. Cruz <jon@joncruz.org>
 *
 * Copyright (C) 2003 MenTaLguY
 *
 * Released under GNU GPL v2+, read the file 'COPYING' for more information.
 */

#include "uri.h"

#include <cstring>

#include <giomm/contenttype.h>
#include <giomm/file.h>
#include <glibmm/base64.h>
#include <glibmm/convert.h>
#include <glibmm/ustring.h>
#include <glibmm/miscutils.h>

#include "bad-uri-exception.h"

namespace Inkscape {

auto const URI_ALLOWED_NON_ALNUM = "!#$%&'()*+,-./:;=?@_~";

/**
 * Return true if the given URI string contains characters that need escaping.
 *
 * Note: It does not check if valid characters appear in invalid context (e.g.
 * '%' not followed by two hex digits).
 */
static bool uri_needs_escaping(char const *uri)
{
    for (auto *p = uri; *p; ++p) {
        if (!g_ascii_isalnum(*p) && !strchr(URI_ALLOWED_NON_ALNUM, *p)) {
            return true;
        }
    }
    return false;
}

URI::URI() {
    init(xmlCreateURI());
}

URI::URI(gchar const *preformed, char const *baseuri)
{
    xmlURIPtr uri;
    if (!preformed) {
        throw MalformedURIException();
    }

    // check for invalid characters, escape if needed
    xmlChar *escaped = nullptr;
    if (uri_needs_escaping(preformed)) {
        escaped = xmlURIEscapeStr(      //
            (xmlChar const *)preformed, //
            (xmlChar const *)URI_ALLOWED_NON_ALNUM);
        preformed = (decltype(preformed))escaped;
    }

    // make absolute
    xmlChar *full = nullptr;
    if (baseuri) {
        full = xmlBuildURI(             //
            (xmlChar const *)preformed, //
            (xmlChar const *)baseuri);
#if LIBXML_VERSION < 20905
        // libxml2 bug: "file:/some/file" instead of "file:///some/file"
        auto f = (gchar const *)full;
        if (f && g_str_has_prefix(f, "file:/") && f[6] != '/') {
            auto fixed = std::string(f, 6) + "//" + std::string(f + 6);
            xmlFree(full);
            full = (xmlChar *)xmlMemStrdup(fixed.c_str());
        }
#endif
        preformed = (decltype(preformed))full;
    }

    uri = xmlParseURI(preformed);

    if (full) {
        xmlFree(full);
    }
    if (escaped) {
        xmlFree(escaped);
    }
    if (!uri) {
        throw MalformedURIException();
    }
    init(uri);
}

URI::URI(char const *preformed, URI const &baseuri)
    : URI::URI(preformed, baseuri.str().c_str())
{
}

// From RFC 2396:
//
// URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
// absoluteURI   = scheme ":" ( hier_part | opaque_part )
// relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
//
// hier_part     = ( net_path | abs_path ) [ "?" query ]
// opaque_part   = uric_no_slash *uric
//
// uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
//                 "&" | "=" | "+" | "$" | ","
//
// net_path      = "//" authority [ abs_path ]
// abs_path      = "/"  path_segments
// rel_path      = rel_segment [ abs_path ]
//
// rel_segment   = 1*( unreserved | escaped |
//                     ";" | "@" | "&" | "=" | "+" | "$" | "," )
//
// authority     = server | reg_name

bool URI::isOpaque() const {
    return getOpaque() != nullptr;
}

bool URI::isRelative() const {
    return !_xmlURIPtr()->scheme;
}

bool URI::isNetPath() const {
    return isRelative() && _xmlURIPtr()->server;
}

bool URI::isRelativePath() const {
    if (isRelative() && !_xmlURIPtr()->server) {
        const gchar *path = getPath();
        return path && path[0] != '/';
    }
    return false;
}

bool URI::isAbsolutePath() const {
    if (isRelative() && !_xmlURIPtr()->server) {
        const gchar *path = getPath();
        return path && path[0] == '/';
    }
    return false;
}

const gchar *URI::getScheme() const {
    return (gchar *)_xmlURIPtr()->scheme;
}

const gchar *URI::getPath() const {
    return (gchar *)_xmlURIPtr()->path;
}

const gchar *URI::getQuery() const {
    return (gchar *)_xmlURIPtr()->query;
}

const gchar *URI::getFragment() const {
    return (gchar *)_xmlURIPtr()->fragment;
}

const gchar *URI::getOpaque() const {
    if (!isRelative() && !_xmlURIPtr()->server) {
        const gchar *path = getPath();
        if (path && path[0] != '/') {
            return path;
        }
    }
    return nullptr;
}

std::string URI::toNativeFilename() const
{ //
    auto uristr = str();

    // remove fragment identifier
    if (getFragment() != nullptr) {
        uristr.resize(uristr.find('#'));
    }

    return Glib::filename_from_uri(uristr);
}

/* TODO !!! proper error handling */
URI URI::from_native_filename(gchar const *path) {
    gchar *uri = g_filename_to_uri(path, nullptr, nullptr);
    URI result(uri);
    g_free( uri );
    return result;
}

URI URI::from_dirname(gchar const *path)
{
    std::string pathstr = path ? path : ".";

    if (!Glib::path_is_absolute(pathstr)) {
        pathstr = Glib::build_filename(Glib::get_current_dir(), pathstr);
    }

    auto uristr = Glib::filename_to_uri(pathstr);

    if (uristr[uristr.size() - 1] != '/') {
        uristr.push_back('/');
    }

    return URI(uristr.c_str());
}

URI URI::from_href_and_basedir(char const *href, char const *basedir)
{
    try {
        return URI(href, URI::from_dirname(basedir));
    } catch (...) {
        return URI();
    }
}

/**
 * Replacement for buggy xmlBuildRelativeURI
 * https://gitlab.gnome.org/GNOME/libxml2/merge_requests/12
 *
 * Special case: Don't cross filesystem root, e.g. drive letter on Windows.
 * This is an optimization to keep things practical, it's not required for correctness.
 *
 * @param uri an absolute URI
 * @param base an absolute URI without any ".." path segments
 * @return relative URI if possible, otherwise @a uri unchanged
 */
static std::string build_relative_uri(char const *uri, char const *base)
{
    size_t n_slash = 0;
    size_t i = 0;

    // find longest common prefix
    for (; uri[i]; ++i) {
        if (uri[i] != base[i]) {
            break;
        }

        if (uri[i] == '/') {
            ++n_slash;
        }
    }

    // URIs must share protocol://server/
    if (n_slash < 3) {
        return uri;
    }

    // Don't cross filesystem root
    if (n_slash == 3 && g_str_has_prefix(base, "file:///") && base[8]) {
        return uri;
    }

    std::string relative;

    for (size_t j = i; base[j]; ++j) {
        if (base[j] == '/') {
            relative += "../";
        }
    }

    while (uri[i - 1] != '/') {
        --i;
    }

    relative += (uri + i);

    if (relative.empty() && base[i]) {
        relative = "./";
    }

    return relative;
}

std::string URI::str(char const *baseuri) const
{
    std::string s;
    auto saveuri = xmlSaveUri(_xmlURIPtr());
    if (saveuri) {
        auto save = (const char *)saveuri;
        if (baseuri && baseuri[0]) {
            s = build_relative_uri(save, baseuri);
        } else {
            s = save;
        }
        xmlFree(saveuri);
    }
    return s;
}

std::string URI::getMimeType() const
{
    const char *path = getPath();

    if (path) {
        if (hasScheme("data")) {
            for (const char *p = path; *p; ++p) {
                if (*p == ';' || *p == ',') {
                    return std::string(path, p);
                }
            }
        } else {
            bool uncertain;
            auto type = Gio::content_type_guess(path, nullptr, 0, uncertain);
            return Gio::content_type_get_mime_type(type).raw();
        }
    }

    return "unknown/unknown";
}

std::string URI::getContents() const
{
    if (hasScheme("data")) {
        // handle data URIs

        const char *p = getPath();
        const char *tok = nullptr;

        // scan "[<media type>][;base64]," header
        for (; *p && *p != ','; ++p) {
            if (*p == ';') {
                tok = p + 1;
            }
        }

        // body follows after comma
        if (*p != ',') {
            g_critical("data URI misses comma");
        } else if (tok && strncmp("base64", tok, p - tok) == 0) {
            // base64 encoded body
            return Glib::Base64::decode(p + 1);
        } else {
            // raw body
            return p + 1;
        }
    } else {
        // handle non-data URIs with GVfs
        auto file = Gio::File::create_for_uri(str());

        gsize length = 0;
        char *buffer = nullptr;

        if (file->load_contents(buffer, length)) {
            auto contents = std::string(buffer, buffer + length);
            g_free(buffer);
            return contents;
        } else {
            g_critical("failed to load contents from %.100s", str().c_str());
        }
    }

    return "";
}

bool URI::hasScheme(const char *scheme) const
{
    const char *s = getScheme();
    return s && g_ascii_strcasecmp(s, scheme) == 0;
}

/**
 * If \c s starts with a "%XX" triplet, return its byte value, 0 otherwise.
 */
static int uri_unescape_triplet(const char *s)
{
    int H1, H2;

    if (s[0] == '%'                                //
        && (H1 = g_ascii_xdigit_value(s[1])) != -1 //
        && (H2 = g_ascii_xdigit_value(s[2])) != -1) {
        return (H1 << 4) | H2;
    }

    return 0;
}

/**
 * If \c s starts with a percent-escaped UTF-8 sequence, unescape one code
 * point and store it in \c out variable. Do nothing and return 0 if \c s
 * doesn't start with UTF-8.
 *
 * @param[in] s percent-escaped string
 * @param[out] out out-buffer, must have at least size 5
 * @return number of bytes read from \c s
 */
static int uri_unescape_utf8_codepoint(const char *s, char *out)
{
    int n = 0;
    int value = uri_unescape_triplet(s);

    if ((value >> 5) == /* 0b110 */ 0x6) {
        // 110xxxxx 10xxxxxx
        n = 2;
    } else if ((value >> 4) == /* 0b1110 */ 0xE) {
        // 1110xxxx 10xxxxxx 10xxxxxx
        n = 3;
    } else if ((value >> 3) == /* 0b11110 */ 0x1E) {
        // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
        n = 4;
    } else {
        return 0;
    }

    out[0] = value;
    out[n] = 0;

    for (int i = 1; i < n; ++i) {
        value = uri_unescape_triplet(s + (i * 3));

        if ((value >> 6) != /* 0b10 */ 0x2) {
            return 0;
        }

        out[i] = value;
    }

    return n * 3;
}

std::string uri_to_iri(const char *uri)
{
    std::string iri;

    char utf8buf[5];

    for (const char *p = uri; *p;) {
        int n = uri_unescape_utf8_codepoint(p, utf8buf);
        if (n) {
            iri.append(utf8buf);
            p += n;
        } else {
            iri += *p;
            p += 1;
        }
    }

    return iri;
}

} // namespace Inkscape


/*
  Local Variables:
  mode:c++
  c-file-style:"stroustrup"
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
  indent-tabs-mode:nil
  fill-column:99
  End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :