summaryrefslogtreecommitdiff
path: root/src/utilfuns/url.cpp
blob: a909a04c8fe76cffe1e9cd5c0881d52b2e97dd0d (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
/******************************************************************************
 *
 *  url.cpp -	code for an URL parser utility class
 *
 * $Id: url.cpp 2980 2013-09-14 21:51:47Z scribe $
 *
 * Copyright 2004-2013 CrossWire Bible Society (http://www.crosswire.org)
 *	CrossWire Bible Society
 *	P. O. Box 2528
 *	Tempe, AZ  85280-2528
 *
 * This program 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 version 2.
 *
 * This program 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.
 *
 */

#include <url.h>
#include <swlog.h>

//system includes
#include <ctype.h>
#include <map>
#include <stdio.h>
#include <iostream>


SWORD_NAMESPACE_START


namespace {
	typedef std::map<unsigned char, SWBuf> DataMap;
    	DataMap m;
	static class __init {
		public:
			__init() {
				for (unsigned short int c = 32; c <= 255; ++c) { //first set all encoding chars
					if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || strchr("-_.!~*'()", c)) {
						continue; //we don't need an encoding for this char
					}

					SWBuf buf;
					buf.setFormatted("%%%-.2X", c);
					m[c] = buf;
				}
				//the special encodings for certain chars
				m[' '] = '+';
			}
	} ___init;
}


/**
 * Constructors/Destructors
 */
URL::URL(const char *url)  
	: 	url(""),
		protocol(""),
		hostname(""),
		path("")
{
	if (url && strlen(url)) {
		this->url = url;
		parse();
	}
}


const char *URL::getProtocol() const {
	return protocol.c_str();
}


const char *URL::getHostName () const {
	return hostname.c_str();
}


const char *URL::getPath() const {
	return path.c_str();
}


const URL::ParameterMap &URL::getParameters() const {
	return parameterMap;
}


/**
 * Returns the value of an URL parameter. For the URL "http://www.crosswire.org/index.jsp?page=test&amp;user=nobody" the value of the parameter "page" would be "test".
 * If the parameter is not set an empty string is returned.
 */
const char *URL::getParameterValue(const char *name) const {
	static SWBuf emptyStr("");

	ParameterMap::const_iterator it = parameterMap.find(name);
	static SWBuf retVal;

	if (it != parameterMap.end())
		retVal = it->second.c_str();
    	else
		retVal = emptyStr.c_str();

	return retVal.c_str();
}


/** Parse the URL.
 * Parse the URL into the protocol, the hostname, the path and the paramters with their values
 * 
 */
void URL::parse() {
	/* format example		protocol://hostname/path/path/path.pl?param1=value1&amp;param2=value2
	* we include the script name in the path, so the path would be /path/path/path.pl in this example
	*  &amp; could also be &
	*/

	//1. Init
	const char *urlPtr = url.c_str();
	 
	protocol = "";
	hostname = "";
	path     = "";
	parameterMap.clear();
	 
	 // 2. Get the protocol, which is from the begining to the first ://
	const char *end = strchr( urlPtr, ':' );
	if (end) { //protocol was found
	 	protocol.append(urlPtr, end-urlPtr);
	 	urlPtr = end + 1;
	
		//find the end of the protocol separator (e.g. "://")
		for (; (*urlPtr == ':') || (*urlPtr == '/'); urlPtr++);
	}

 //3.Get the hostname part. This is the part from pos up to the first slash
	bool checkPath   = true;
	bool checkParams = true;
	bool checkAnchor = true;

	end = strchr(urlPtr, '/');
	if (!end) {
		checkPath = false;
		end = strchr(urlPtr, '?');
	}
	if (!end) {
		checkParams = false;
		end = strchr(urlPtr, '#');
	}
	if (!end) {
		checkAnchor = false;
		end = urlPtr+strlen(urlPtr);
	}
	 
	hostname.append(urlPtr, end-urlPtr);
	 	
	urlPtr = end + ((*end)? 1 : 0);

	if (checkPath) { 
		end = strchr(urlPtr, '?');
		if (!end) {
			checkParams = false;
			end = strchr(urlPtr, '#');
		}
		if (!end) {
			checkAnchor = false;
			end = urlPtr+strlen(urlPtr);
		}

	 	path.append(urlPtr, end-urlPtr);
		
		urlPtr = end + ((*end)? 1 : 0);
	 }

	if (checkParams) {
		//5. Fill the map with the parameters and their values
		SWBuf paramName;
		SWBuf paramValue;
				
		if (checkAnchor) checkAnchor = false;
/*
		end = strchr(urlPtr, '#');
		if (!end) {
			checkAnchor = false;
			end = urlPtr+strlen(urlPtr);
		}
*/
		//end = (start && strchr(start, '?')) ? strchr(start, '?')+1 :0;
		end = urlPtr;
		while (end) {
			paramName = "";
			paramValue = "";
			
			//search for the equal sign to find the value part
			const char *valueStart = strchr(end, '=');		
			if (valueStart) {
				const char* valueEnd = strstr(valueStart, "&amp;") ? strstr(valueStart, "&amp;") : strstr(valueStart, "&"); //try to find a new paramter part
				
				if (valueEnd) {
					paramName.append(end, valueStart-end);
					paramValue.append(valueStart+1, valueEnd-(valueStart+1));
				}
				else { //this is the last paramter of the URL
					paramName.append(end, valueStart-end);
					paramValue.append(valueStart+1);
				}
				
				if (paramName.length() && paramValue.length()) {//insert the param into the map if it's valid
					paramName = decode(paramName.c_str());
					paramValue = decode(paramValue.c_str());
					
					parameterMap[ paramName ] = paramValue;
				}
			}
			else {
				break; //no valid parameter in the url
			}
			
			const char *start = end+1;
			end = strstr(start, "&amp;") ? strstr(start, "&amp;")+5 : (strstr(start, "&") ? strstr(start, "&")+1 : 0); //try to find a new paramter part
		}
	}
}


const SWBuf URL::encode(const char *urlText) {
	/*static*/ SWBuf url;
	url = urlText;
	
	SWBuf buf;
	const int length = url.length();
	for (int i = 0; i < length; i++) { //fill "buf"
		const char& c = url[i];
		buf.append( ((m[c].length()) ? m[c] : SWBuf(c)) );
	}

	url = buf;
	return url;
}


const SWBuf URL::decode(const char *encoded) {
	/*static*/ SWBuf text;
	text = encoded;	

	SWBuf decoded;	
	const int length = text.length();
	int i = 0;
	
	while (i < length) {
		char a = text[i];
		
		if ( a == '+' ) { //handle special cases
			decoded.append(' ');
		}		
		else if ( (a == '%') && (i+2 < length)) { //decode the %ab  hex encoded char
			const char b = toupper( text[i+1] );
			const char c = toupper( text[i+2] );
			
			if (isxdigit(b) && isxdigit(c)) { //valid %ab part
				unsigned int dec = 16 * ((b >= 'A' && b <= 'F') ? (b - 'A' + 10) : (b - '0')); //dec value of the most left digit (b)
				dec += (c >= 'A' && c <= 'F') ? (c - 'A' + 10) : (c - '0'); //dec value of the right digit (c)
				
				decoded.append((char)dec); //append the decoded char
				
				i += 2; //we jump over the %ab part; we have to leave out three, but the while  loop adds one, too
			}
		}
		else { //just append the char
			decoded.append(a);
		}
		
		i++;
	}
	
	if (decoded.length()) {
		text = decoded;
	}
	return text;
}


SWORD_NAMESPACE_END