2 * This file is part of DisOrder.
3 * Copyright (C) 2004, 2005 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
34 int urldecode(struct sink *sink, const char *ptr, size_t n) {
40 if((d1 = unhexdigit(ptr[0])) == -1
41 || (d2 = unhexdigit(ptr[1])) == -1)
53 if(sink_writec(sink,c) < 0)
59 static char *decode(const char *ptr, size_t n) {
65 if(urldecode(s, ptr, n))
71 struct kvp *kvp_urldecode(const char *ptr, size_t n) {
72 struct kvp *kvp, **kk = &kvp, *k;
73 const char *q, *r, *top = ptr + n, *next;
76 *kk = k = xmalloc(sizeof *k);
77 if(!(q = memchr(ptr, '=', top - ptr)))
79 if(!(k->name = decode(ptr, q - ptr))) break;
80 if((r = memchr(ptr, '&', top - ptr)))
86 if(!(k->value = decode(q + 1, r - (q + 1)))) break;
94 int urlencode(struct sink *sink, const char *s, size_t n) {
102 if((c >= '0' && c <= '9')
103 || (c >= 'a' && c <= 'z')
104 || (c >= 'A' && c <= 'Z')) {
105 /* RFC2396 2.3 unreserved characters */
115 /* additional unreserved characters */
117 if(sink_writec(sink, c) < 0)
120 if(sink_printf(sink, "%%%02x", (unsigned int)c) < 0)
127 const char *urlencodestring(const char *s) {
131 urlencode(sink_dynstr(&d), s, strlen(s));
132 dynstr_terminate(&d);
136 char *kvp_urlencode(const struct kvp *kvp, size_t *np) {
141 sink = sink_dynstr(&d);
143 urlencode(sink, kvp->name, strlen(kvp->name));
144 dynstr_append(&d, '=');
145 urlencode(sink, kvp->value, strlen(kvp->value));
146 if((kvp = kvp->next))
147 dynstr_append(&d, '&');
150 dynstr_terminate(&d);
156 int kvp_set(struct kvp **kvpp, const char *name, const char *value) {
159 for(kk = kvpp; (k = *kk) && strcmp(name, k->name); kk = &k->next)
163 if(strcmp(k->value, value)) {
164 k->value = xstrdup(value);
174 *kk = k = xmalloc(sizeof *k);
175 k->name = xstrdup(name);
176 k->value = xstrdup(value);
183 const char *kvp_get(const struct kvp *kvp, const char *name) {
184 for(;kvp && strcmp(kvp->name, name); kvp = kvp->next)
186 return kvp ? kvp->value : 0;