File: URL.cpp

package info (click to toggle)
freespace2 24.2.0%2Brepack-3
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,740 kB
  • sloc: cpp: 595,005; ansic: 21,741; python: 1,174; sh: 457; makefile: 243; xml: 181
file content (626 lines) | stat: -rw-r--r-- 13,310 bytes parent folder | download | duplicates (2)
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/*
 * This source file is part of libRocket, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://www.librocket.com
 *
 * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include "precompiled.h"
#include "../../Include/Rocket/Core/URL.h"
#include <stdio.h>

namespace Rocket {
namespace Core {

const char* DEFAULT_PROTOCOL = "file";

// Constructs an Empty URL.
URL::URL()
{
	port = 0;
	url_dirty = false;
}

// Constructs a new URL from the given string.
URL::URL(const String& _url)
{
	port = 0;
	ROCKET_VERIFY(SetURL(_url));
}

// Constructs a new URL from the given string.
URL::URL(const char* _url)
{
	port = 0;
	ROCKET_VERIFY(SetURL(_url));
}

// Destroys the URL.
URL::~URL()
{
}

// Assigns a new URL to the object.
bool URL::SetURL(const String& _url)
{
	url_dirty = false;
	url = _url;

	// Make sure an Empty URL is completely Empty.
	if (url.Empty())
	{
		protocol.Clear();
		login.Clear();
		password.Clear();
		host.Clear();
		port = 0;
		path.Clear();
		file_name.Clear();
		extension.Clear();

		return true;
	}

	// Find the protocol. This consists of the string appearing before the
	// '://' token (ie, file://, http://).
	const char* host_begin = strchr(_url.CString(), ':');
	if (NULL != host_begin)
	{
		protocol.Assign(_url.CString(), host_begin);
		if (0 != strncmp(host_begin, "://", 3))
		{
			char malformed_terminator[4] = {0, 0, 0, 0};
			strncpy(malformed_terminator, host_begin, 3);
			Log::Message(Log::LT_ERROR, "Malformed protocol identifier found in URL %s; expected %s://, found %s%s.\n", _url.CString(), protocol.CString(), protocol.CString(), malformed_terminator);

			return false;
		}
		host_begin += 3;
	}
	else
	{
		protocol = DEFAULT_PROTOCOL;
		host_begin = _url.CString();
	}


	// We only want to look for a host if a protocol was specified.
	const char* path_begin;
	if (host_begin != _url.CString())
	{
		// Find the host. This is the string appearing after the protocol or after
		// the username:password combination, and terminated either with a colon, 
		// if a port is specified, or a forward slash if there is no port.

		// Check for a login pair
		const char* at_symbol = strchr( host_begin, '@' );
		if ( at_symbol )
		{
			String login_password;
			login_password.Assign( host_begin, at_symbol );			
			host_begin = at_symbol + 1;

			const char* password_ptr = strchr( login_password.CString(), ':' );
			if ( password_ptr )
			{
				login.Assign( login_password.CString(), password_ptr );
				password.Assign( password_ptr + 1 );
			}
			else
			{
				login = login_password;
			}
		}

		// Get the host portion
		path_begin = strchr(host_begin, '/');
		// Search for the colon in the host name, which will indicate a port.
		const char* port_begin = strchr(host_begin, ':');
		if (NULL != port_begin && (NULL == path_begin || port_begin < path_begin))
		{
			if (1 != sscanf(port_begin, ":%d", &port))
			{
				Log::Message(Log::LT_ERROR, "Malformed port number found in URL %s.\n", _url.CString());
				return false;
			}

			host.Assign(host_begin, port_begin);

			// Don't continue if there is no path.
			if (NULL == path_begin)
			{
				return true;
			}

			// Increment the path string past the trailing slash.
			++path_begin;
		}
		else
		{
			port = -1;

			if (NULL == path_begin)
			{
				host = host_begin;
				return true;
			}
			else
			{
				// Assign the host name, then increment the path string past the
				// trailing slash.
				host.Assign(host_begin, path_begin);
				++path_begin;
			}
		}
	}
	else
	{
		path_begin = _url.CString();
	}
	
	// Check for parameters
	String path_segment;
	const char* parameters = strchr(path_begin, '?');
	if ( parameters )
	{
		// Pull the path segment out, so further processing doesn't read the parameters
		path_segment.Assign(path_begin, parameters);
		path_begin = path_segment.CString();
		
		// Loop through all parameters, loading them
		StringList parameter_list;
		StringUtilities::ExpandString( parameter_list, parameters + 1, '&' );
		for ( size_t i = 0; i < parameter_list.size(); i++ )
		{
			// Split into key and value
			StringList key_value;
			StringUtilities::ExpandString( key_value, parameter_list[i], '=' );

			key_value[0] = UrlDecode(key_value[0]);
			if ( key_value.size() == 2 )
				this->parameters[key_value[0]] = UrlDecode(key_value[1]);
			else
				this->parameters[key_value[0]] = "";
		}
	}


	// Find the path. This is the string appearing after the host, terminated
	// by the last forward slash.
	const char* file_name_begin = strrchr(path_begin, '/');
	if (NULL == file_name_begin)
	{
		// No path!
		file_name_begin = path_begin;
		path = "";
	}
	else
	{
		// Copy the path including the trailing slash.
		path.Assign(path_begin, ++file_name_begin);

		// Normalise the path, stripping any ../'s from it
		size_t parent_dir_pos = String::npos;
		while ((parent_dir_pos = path.Find("/..")) != String::npos)
		{
			// If we found a /.. we should be able to find the start of the parent
			// directory, if we can't something wierd has happend, bail
			size_t parent_dir_start_pos = path.RFind("/", parent_dir_pos);
			if (parent_dir_start_pos == String::npos)
				break;

			// Strip out the parent dir and the /..
			path.Erase(parent_dir_start_pos, parent_dir_pos - parent_dir_start_pos + 3);

			// We've altered the URL, mark it dirty
			url_dirty = true;
		}
	}


	// Find the file name. This is the string after the trailing slash of the
	// path, and just before the extension.
	const char* extension_begin = strrchr(file_name_begin, '.');
	if (NULL == extension_begin)
	{
		file_name = file_name_begin;
		extension = "";
	}
	else
	{
		file_name.Assign(file_name_begin, extension_begin);
		extension = extension_begin + 1;
	}
	
	return true;
}

// Returns the entire URL.
const String& URL::GetURL() const
{
	if (url_dirty)
		ConstructURL();
	
	return url;
}

// Sets the URL's protocol.
bool URL::SetProtocol(const String& _protocol)
{
	protocol = _protocol;
	url_dirty = true;

	return true;
}

// Returns the protocol this URL is utilising.
const String& URL::GetProtocol() const
{
	return protocol;
}

/// Sets the URL's login
bool URL::SetLogin( const String& _login )
{
	login = _login;
	url_dirty = true;
	return true;
}

/// Returns the URL's login
const String& URL::GetLogin() const
{
	return login;
}

/// Sets the URL's password
bool URL::SetPassword(const String& _password)
{
	password = _password;
	url_dirty = true;
	return true;
}

/// Returns the URL's password
const String& URL::GetPassword() const
{
	return password;
}

// Sets the URL's host.
bool URL::SetHost(const String& _host)
{
	host = _host;
	url_dirty = true;

	return true;
}

// Returns the URL's host.
const String& URL::GetHost() const
{
	return host;
}

// Sets the URL's port number.
bool URL::SetPort(int _port)
{
	port = _port;
	url_dirty = true;

	return true;
}

// Returns the URL's port number.
int URL::GetPort() const
{
	return port;
}

// Sets the URL's path.
bool URL::SetPath(const String& _path)
{
	path = _path;
	url_dirty = true;

	return true;
}

// Prefixes the URL's existing path with the given prefix.
bool URL::PrefixPath(const String& prefix)
{
	// If there's no trailing slash on the end of the prefix, add one.
	if (!prefix.Empty() &&
		prefix[prefix.Length() - 1] != '/')
		path = prefix + "/" + path;
	else
		path = prefix + path;

	url_dirty = true;

	return true;
}

// Returns the URL's path.
const String& URL::GetPath() const
{
	return path;
}

// Sets the URL's file name.
bool URL::SetFileName(const String& _file_name)
{
	file_name = _file_name;
	url_dirty = true;

	return true;
}

// Returns the URL's file name.
const String& URL::GetFileName() const
{
	return file_name;
}

// Sets the URL's file extension.
bool URL::SetExtension(const String& _extension)
{
	extension = _extension;
	url_dirty = true;

	return true;
}

// Returns the URL's file extension.
const String& URL::GetExtension() const
{
	return extension;
}

// Gets the current parameters
const URL::Parameters& URL::GetParameters() const
{
	return parameters;
}

// Set an individual parameter
void URL::SetParameter(const String& key, const String& value)
{
	parameters[key] = value;
	url_dirty = true;
}

// Set all parameters
void URL::SetParameters(const Parameters& _parameters)
{
	parameters = _parameters;
	url_dirty = true;
}

// Clear the parameters
void URL::ClearParameters()
{
	parameters.clear();
}

// Returns the URL's path, file name and extension.
String URL::GetPathedFileName() const
{
	String pathed_file_name = path;
	
	// Append the file name.
	pathed_file_name += file_name;
	
	// Append the extension.
	if (!extension.Empty())
	{
		pathed_file_name.Append(".");
		pathed_file_name += extension;
	}
	
	return pathed_file_name;
}

String URL::GetQueryString() const
{
	String query_string;
	
	int count = 0;
	for ( Parameters::const_iterator itr = parameters.begin(); itr != parameters.end(); ++itr )
	{
		query_string += ( count == 0 ) ? "" : "&";
		
		query_string += UrlEncode((*itr).first);
		query_string += "=";
		query_string += UrlEncode((*itr).second);
		
		count++;
	}
	
	return query_string;
}

// Less-than operator for use as a key in STL containers.
bool URL::operator<(const URL& rhs) const
{
	if (url_dirty)
		ConstructURL();
	if (rhs.url_dirty)
		rhs.ConstructURL();
	
	return url < rhs.url;
}

void URL::ConstructURL() const
{
	url = "";

	// Append the protocol.
	if (!protocol.Empty() && !host.Empty())	
	{
		url = protocol;
		url.Append("://");
	}

	// Append login and password
	if (!login.Empty())
	{
		url.Append( login );
		if (!password.Empty())
		{		
			url.Append( ":" );
			url.Append( password );
		}
		url.Append( "@" );
	}
	ROCKET_ASSERTMSG( password.Empty() || ( !password.Empty() && !login.Empty() ), "Can't have a password without a login!" );

	// Append the host.
	url += host;
	
	// Only check ports if there is some host/protocol part
	if ( !url.Empty() )
	{		
		if (port > 0)
		{
			ROCKET_ASSERTMSG( !host.Empty(), "Can't have a port without a host!" );
			char port_string[16];
			sprintf(port_string, ":%d/", port);
			url.Append(port_string);
		}
		else
		{
			url.Append("/");
		}
	}

	// Append the path.
	if (!path.Empty())
	{
		url += path;
	}

	// Append the file name.
	url += file_name;

	// Append the extension.
	if (!extension.Empty())
	{
		url.Append(".");
		url += extension;
	}
	
	// Append parameters
	if (!parameters.empty())
	{
		url += "?";
		url += GetQueryString();		
	}
	
	url_dirty = false;
}

String URL::UrlEncode(const String &value)
{
	String encoded;
	char hex[4] = {0,0,0,0};

	encoded.Clear();

	const char *value_c = value.CString();
	for (String::size_type i = 0; value_c[i]; i++) 
	{
		char c = value_c[i];
		if (IsUnreservedChar(c))
			encoded.Append(c);
		else
		{
			sprintf(hex, "%%%02X", c);
			encoded.Append(hex);
		}
	}

	return encoded;
}

String URL::UrlDecode(const String &value)
{
	String decoded;

	decoded.Clear();

	const char *value_c = value.CString();
	String::size_type value_len = value.Length();
	for (String::size_type i = 0; i < value_len; i++) 
	{
		char c = value_c[i];
		if (c == '+')
		{
			decoded.Append(' ' );
		}
		else if (c == '%')
		{
			char *endp;
			String t = value.Substring(i+1, 2);
			int ch = strtol(t.CString(), &endp, 16);
			if (*endp == '\0')
				decoded.Append(char(ch));
			else
				decoded.Append(t);
			i += 2;
		}
		else
		{
			decoded.Append(c);
		}
	}

	return decoded;
}

bool URL::IsUnreservedChar(const char in)
{
	switch (in)
	{
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
		case 'a': case 'b': case 'c': case 'd': case 'e':
		case 'f': case 'g': case 'h': case 'i': case 'j':
		case 'k': case 'l': case 'm': case 'n': case 'o':
		case 'p': case 'q': case 'r': case 's': case 't':
		case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
		case 'A': case 'B': case 'C': case 'D': case 'E':
		case 'F': case 'G': case 'H': case 'I': case 'J':
		case 'K': case 'L': case 'M': case 'N': case 'O':
		case 'P': case 'Q': case 'R': case 'S': case 'T':
		case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
		case '-': case '.': case '_': case '~':
			return true;
		default:
			break;
	}
	return false;
}

}
}