SAML 1.x SSO assertion validator.
[shibboleth/cpp-opensaml.git] / saml / binding / impl / URLEncoder.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * URLEncoder.cpp
19  * 
20  * Interface to a URL-encoding mechanism along with a
21  * default implementation. 
22  */
23
24 #include "internal.h"
25 #include "binding/URLEncoder.h"
26
27 using namespace opensaml;
28 using namespace std;
29
30 static char x2c(char *what)
31 {
32     register char digit;
33
34     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
35     digit *= 16;
36     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
37     return(digit);
38 }
39
40 void URLEncoder::decode(char* s) const
41 {
42     register int x,y;
43
44     for(x=0,y=0;s[y];++x,++y)
45     {
46         if((s[x] = s[y]) == '%')
47         {
48             s[x] = x2c(&s[y+1]);
49             y+=2;
50         }
51         else if (s[x] == '+')
52         {
53             s[x] = ' ';
54         }
55     }
56     s[x] = '\0';
57 }
58
59 static inline char hexchar(unsigned short s)
60 {
61     return (s<=9) ? ('0' + s) : ('A' + s - 10);
62 }
63
64 string URLEncoder::encode(const char* s) const
65 {
66     string ret;
67     for (; *s; s++) {
68         if (isBad(*s)) {
69             ret+='%';
70             ret+=hexchar((unsigned char)*s >> 4);
71             ret+=hexchar((unsigned char)*s & 0x0F);
72         }
73         else
74             ret+=*s;
75     }
76     return ret;
77 }