summaryrefslogtreecommitdiffstats
path: root/tinySAK/src/tsk_url.c
blob: cf4417bf626306c17cb4406748633dd7668227f8 (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
/*
* Copyright (C) 2010-2015 Mamadou DIOP.
*
* This file is part of Open Source Doubango Framework.
*
* DOUBANGO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DOUBANGO 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DOUBANGO.
*
*/

/**@file tsk_url.c
 * @brief Utility functions to encode/decode urls.
 *
 */
#include "tsk_url.h"
#include "tsk_memory.h"
#include "tsk_string.h"

#include <ctype.h>
#include <string.h>

/**@defgroup tsk_url_group Utility functions to encode/decode urls.
*/


/**@ingroup tsk_url_group
* Encode an url.
* @param url The url to encode
* @retval The encoded url. It is up to you to free the returned string.
*
* @sa tsk_url_decode
*
*/
char* tsk_url_encode(const char* url)
{
    char *purl = (char*)url, *buf = (char*)tsk_malloc(tsk_strlen(url) * 3 + 1), *pbuf = buf;
    while (*purl) {
        if (isalnum(*purl) || *purl == '-' || *purl == '_' || *purl == '.' || *purl == '~') {
            *pbuf++ = *purl;
        }
        else if (*purl == ' ') {
            *pbuf++ = '+';
        }
        else {
            *pbuf++ = '%', *pbuf++ = tsk_b10tob16(*purl >> 4), *pbuf++ = tsk_b10tob16(*purl & 15);
        }
        purl++;
    }
    *pbuf = '\0';
    return buf;
}

/**@ingroup tsk_url_group
* Decode an url.
* @param url The url to encode
* @retval The decoded url. It is up to you to free the returned string.
*
* @sa tsk_url_encode
*/
char* tsk_url_decode(const char* url)
{
    char *purl = (char*)url, *buf = (char*)tsk_malloc(tsk_strlen(url) + 1), *pbuf = buf;
    while (*purl) {
        if (*purl == '%') {
            if (purl[1] && purl[2]) {
                *pbuf++ = tsk_b16tob10(purl[1]) << 4 | tsk_b16tob10(purl[2]);
                purl += 2;
            }
        }
        else if (*purl == '+') {
            *pbuf++ = ' ';
        }
        else {
            *pbuf++ = *purl;
        }
        purl++;
    }
    *pbuf = '\0';
    return buf;
}

OpenPOWER on IntegriCloud