ASIWebPageRequest.m 28.4 KB
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 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
//
//  ASIWebPageRequest.m
//  Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
//  Created by Ben Copsey on 29/06/2010.
//  Copyright 2010 All-Seeing Interactive. All rights reserved.
//
//  This is an EXPERIMENTAL class - use at your own risk!

#import "ASIWebPageRequest.h"
#import "ASINetworkQueue.h"
#import <CommonCrypto/CommonHMAC.h>

// An xPath query that controls the external resources ASIWebPageRequest will fetch
// By default, it will fetch stylesheets, javascript files, images, frames, iframes, and html 5 video / audio
static xmlChar *xpathExpr = (xmlChar *)"//link/@href|//a/@href|//script/@src|//img/@src|//frame/@src|//iframe/@src|//style|//*/@style|//source/@src|//video/@poster|//audio/@src";

static NSLock *xmlParsingLock = nil;
static NSMutableArray *requestsUsingXMLParser = nil;

@interface ASIWebPageRequest ()
- (void)readResourceURLs;
- (void)updateResourceURLs;
- (void)parseAsHTML;
- (void)parseAsCSS;
- (void)addURLToFetch:(NSString *)newURL;
+ (NSArray *)CSSURLsFromString:(NSString *)string;
- (NSString *)relativePathTo:(NSString *)destinationPath fromPath:(NSString *)sourcePath;

- (void)finishedFetchingExternalResources:(ASINetworkQueue *)queue;
- (void)externalResourceFetchSucceeded:(ASIHTTPRequest *)externalResourceRequest;
- (void)externalResourceFetchFailed:(ASIHTTPRequest *)externalResourceRequest;

@property (retain, nonatomic) ASINetworkQueue *externalResourceQueue;
@property (retain, nonatomic) NSMutableDictionary *resourceList;
@end

@implementation ASIWebPageRequest

+ (void)initialize
{
	if (self == [ASIWebPageRequest class]) {
		xmlParsingLock = [[NSLock alloc] init];
		requestsUsingXMLParser = [[NSMutableArray alloc] init];
	}
}

- (void)dealloc
{
	[externalResourceQueue cancelAllOperations];
	[externalResourceQueue release];
	[resourceList release];
	[parentRequest release];
	[super dealloc];
}

// This is a bit of a hack
// The role of this method in normal ASIHTTPRequests is to tell the queue we are done with the request, and perform some cleanup
// We override it to stop that happening, and instead do that work in the bottom of finishedFetchingExternalResources:
- (void)markAsFinished
{
}

// This method is normally responsible for telling delegates we are done, but it happens to be the most convenient place to parse the responses
// Again, we call the super implementation in finishedFetchingExternalResources:, or here if this download was not an HTML or CSS file
- (void)requestFinished
{
	complete = NO;
	if ([self mainRequest] || [self didUseCachedResponse]) {
		[super requestFinished];
		[super markAsFinished];
		return;
	}
	webContentType = ASINotParsedWebContentType;
	NSString *contentType = [[[self responseHeaders] objectForKey:@"Content-Type"] lowercaseString];
	contentType = [[contentType componentsSeparatedByString:@";"] objectAtIndex:0];
	if ([contentType isEqualToString:@"text/html"] || [contentType isEqualToString:@"text/xhtml"] || [contentType isEqualToString:@"text/xhtml+xml"] || [contentType isEqualToString:@"application/xhtml+xml"]) {
		[self parseAsHTML];
		return;
	} else if ([contentType isEqualToString:@"text/css"]) {
		[self parseAsCSS];
		return;
	}
	[super requestFinished];
	[super markAsFinished];
}

- (void)parseAsCSS
{
	webContentType = ASICSSWebContentType;

	NSString *responseCSS = nil;
	NSError *err = nil;
	if ([self downloadDestinationPath]) {
		responseCSS = [NSString stringWithContentsOfFile:[self downloadDestinationPath] encoding:[self responseEncoding] error:&err];
	} else {
		responseCSS = [self responseString];
	}
	if (err) {
		[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:100 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to read HTML string from response",NSLocalizedDescriptionKey,err,NSUnderlyingErrorKey,nil]]];
		return;
	} else if (!responseCSS) {
		[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:100 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to read HTML string from response",NSLocalizedDescriptionKey,nil]]];
		return;
	}
	NSArray *urls = [[self class] CSSURLsFromString:responseCSS];

	[self setResourceList:[NSMutableDictionary dictionary]];

	for (NSString *theURL in urls) {
		[self addURLToFetch:theURL];
	}
	if (![[self resourceList] count]) {
		[super requestFinished];
		[super markAsFinished];
		return;
	}

	// Create a new request for every item in the queue
	[[self externalResourceQueue] cancelAllOperations];
	[self setExternalResourceQueue:[ASINetworkQueue queue]];
	[[self externalResourceQueue] setDelegate:self];
	[[self externalResourceQueue] setShowAccurateProgress:[self showAccurateProgress]];
	[[self externalResourceQueue] setQueueDidFinishSelector:@selector(finishedFetchingExternalResources:)];
	[[self externalResourceQueue] setRequestDidFinishSelector:@selector(externalResourceFetchSucceeded:)];
	[[self externalResourceQueue] setRequestDidFailSelector:@selector(externalResourceFetchFailed:)];
	for (NSString *theURL in [[self resourceList] keyEnumerator]) {
		ASIWebPageRequest *externalResourceRequest = [ASIWebPageRequest requestWithURL:[NSURL URLWithString:theURL relativeToURL:[self url]]];
		[externalResourceRequest setRequestHeaders:[self requestHeaders]];
		[externalResourceRequest setDownloadCache:[self downloadCache]];
		[externalResourceRequest setCachePolicy:[self cachePolicy]];
		[externalResourceRequest setCacheStoragePolicy:[self cacheStoragePolicy]];
		[externalResourceRequest setUserInfo:[NSDictionary dictionaryWithObject:theURL forKey:@"Path"]];
		[externalResourceRequest setParentRequest:self];
		[externalResourceRequest setUrlReplacementMode:[self urlReplacementMode]];
		[externalResourceRequest setShouldResetDownloadProgress:NO];
		[externalResourceRequest setDelegate:self];
		[externalResourceRequest setUploadProgressDelegate:self];
		[externalResourceRequest setDownloadProgressDelegate:self];
		if ([self downloadDestinationPath]) {
			[externalResourceRequest setDownloadDestinationPath:[self cachePathForRequest:externalResourceRequest]];
		}
		[[self externalResourceQueue] addOperation:externalResourceRequest];
	}
	[[self externalResourceQueue] go];
}

- (void)parseAsHTML
{
	webContentType = ASIHTMLWebContentType;

	// Only allow parsing of a single document at a time
	[xmlParsingLock lock];

	if (![requestsUsingXMLParser count]) {
		xmlInitParser();
	}
	[requestsUsingXMLParser addObject:self];


    /* Load XML document */
	if ([self downloadDestinationPath]) {
		doc = htmlReadFile([[self downloadDestinationPath] cStringUsingEncoding:NSUTF8StringEncoding], NULL, HTML_PARSE_NONET | HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);
	} else {
		NSData *data = [self responseData];
		doc = htmlReadMemory([data bytes], (int)[data length], "", NULL, HTML_PARSE_NONET | HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);
	}
    if (doc == NULL) {
		[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to parse reponse XML",NSLocalizedDescriptionKey,nil]]];
		return;
    }
	
	[self setResourceList:[NSMutableDictionary dictionary]];

    // Populate the list of URLS to download
    [self readResourceURLs];

	if ([self error] || ![[self resourceList] count]) {
		[requestsUsingXMLParser removeObject:self];
		xmlFreeDoc(doc);
		doc = NULL;
	}

	[xmlParsingLock unlock];

	if ([self error]) {
		return;
	} else if (![[self resourceList] count]) {
		[super requestFinished];
		[super markAsFinished];
		return;
	}
	
	// Create a new request for every item in the queue
	[[self externalResourceQueue] cancelAllOperations];
	[self setExternalResourceQueue:[ASINetworkQueue queue]];
	[[self externalResourceQueue] setDelegate:self];
	[[self externalResourceQueue] setShowAccurateProgress:[self showAccurateProgress]];
	[[self externalResourceQueue] setQueueDidFinishSelector:@selector(finishedFetchingExternalResources:)];
	[[self externalResourceQueue] setRequestDidFinishSelector:@selector(externalResourceFetchSucceeded:)];
	[[self externalResourceQueue] setRequestDidFailSelector:@selector(externalResourceFetchFailed:)];
	for (NSString *theURL in [[self resourceList] keyEnumerator]) {
		ASIWebPageRequest *externalResourceRequest = [ASIWebPageRequest requestWithURL:[NSURL URLWithString:theURL relativeToURL:[self url]]];
		[externalResourceRequest setRequestHeaders:[self requestHeaders]];
		[externalResourceRequest setDownloadCache:[self downloadCache]];
		[externalResourceRequest setCachePolicy:[self cachePolicy]];
		[externalResourceRequest setCacheStoragePolicy:[self cacheStoragePolicy]];
		[externalResourceRequest setUserInfo:[NSDictionary dictionaryWithObject:theURL forKey:@"Path"]];
		[externalResourceRequest setParentRequest:self];
		[externalResourceRequest setUrlReplacementMode:[self urlReplacementMode]];
		[externalResourceRequest setShouldResetDownloadProgress:NO];
		[externalResourceRequest setDelegate:self];
		[externalResourceRequest setUploadProgressDelegate:self];
		[externalResourceRequest setDownloadProgressDelegate:self];
		if ([self downloadDestinationPath]) {
			[externalResourceRequest setDownloadDestinationPath:[self cachePathForRequest:externalResourceRequest]];
		}
		[[self externalResourceQueue] addOperation:externalResourceRequest];
	}
	[[self externalResourceQueue] go];
}

- (void)externalResourceFetchSucceeded:(ASIHTTPRequest *)externalResourceRequest
{
	NSString *originalPath = [[externalResourceRequest userInfo] objectForKey:@"Path"];
	NSMutableDictionary *requestResponse = [[self resourceList] objectForKey:originalPath];
	NSString *contentType = [[externalResourceRequest responseHeaders] objectForKey:@"Content-Type"];
	if (!contentType) {
		contentType = @"application/octet-stream";
	}
	[requestResponse setObject:contentType forKey:@"ContentType"];
	if ([self downloadDestinationPath]) {
		[requestResponse setObject:[externalResourceRequest downloadDestinationPath] forKey:@"DataPath"];
	} else {
		NSData *data = [externalResourceRequest responseData];
		if (data) {
			[requestResponse setObject:data forKey:@"Data"];
		}
	}
}

- (void)externalResourceFetchFailed:(ASIHTTPRequest *)externalResourceRequest
{
	[self failWithError:[externalResourceRequest error]];
}

- (void)finishedFetchingExternalResources:(ASINetworkQueue *)queue
{
	if ([self urlReplacementMode] != ASIDontModifyURLs) {
		if (webContentType == ASICSSWebContentType) {
			NSMutableString *parsedResponse;
			NSError *err = nil;
			if ([self downloadDestinationPath]) {
				parsedResponse = [NSMutableString stringWithContentsOfFile:[self downloadDestinationPath] encoding:[self responseEncoding] error:&err];
			} else {
				parsedResponse = [[[self responseString] mutableCopy] autorelease];
			}
			if (err) {
				[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to read response CSS from disk",NSLocalizedDescriptionKey,nil]]];
				return;
			}
			if (![self error]) {
				for (NSString *resource in [[self resourceList] keyEnumerator]) {
					if ([parsedResponse rangeOfString:resource].location != NSNotFound) {
						NSString *newURL = [self contentForExternalURL:resource];
						if (newURL) {
							[parsedResponse replaceOccurrencesOfString:resource withString:newURL options:0 range:NSMakeRange(0, [parsedResponse length])];
						}
					}
				}
			}
			if ([self downloadDestinationPath]) {
				[parsedResponse writeToFile:[self downloadDestinationPath] atomically:NO encoding:[self responseEncoding] error:&err];
				if (err) {
					[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to write response CSS to disk",NSLocalizedDescriptionKey,nil]]];
					return;
				}
			} else {
				[self setRawResponseData:(id)[parsedResponse dataUsingEncoding:[self responseEncoding]]];
			}
		} else {
			[xmlParsingLock lock];

			[self updateResourceURLs];

			if (![self error]) {

				// We'll use the xmlsave API so we can strip the xml declaration
				xmlSaveCtxtPtr saveContext;

				if ([self downloadDestinationPath]) {
					saveContext = xmlSaveToFd([[NSFileHandle fileHandleForWritingAtPath:[self downloadDestinationPath]] fileDescriptor],NULL,2); // 2 == XML_SAVE_NO_DECL, this isn't declared on Mac OS 10.5
					xmlSaveDoc(saveContext, doc);
					xmlSaveClose(saveContext);

				} else {
	#if TARGET_OS_MAC && MAC_OS_X_VERSION_MAX_ALLOWED <= __MAC_10_5
					// xmlSaveToBuffer() is not implemented in the 10.5 version of libxml
					NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
					[[[[NSFileManager alloc] init] autorelease] createFileAtPath:tempPath contents:nil attributes:nil];
					saveContext = xmlSaveToFd([[NSFileHandle fileHandleForWritingAtPath:tempPath] fileDescriptor],NULL,2); // 2 == XML_SAVE_NO_DECL, this isn't declared on Mac OS 10.5
					xmlSaveDoc(saveContext, doc);
					xmlSaveClose(saveContext);
					[self setRawResponseData:[NSMutableData dataWithContentsOfFile:tempPath]];
	#else
					xmlBufferPtr buffer = xmlBufferCreate();
					saveContext = xmlSaveToBuffer(buffer,NULL,2); // 2 == XML_SAVE_NO_DECL, this isn't declared on Mac OS 10.5
					xmlSaveDoc(saveContext, doc);
					xmlSaveClose(saveContext);
					[self setRawResponseData:[[[NSMutableData alloc] initWithBytes:buffer->content length:buffer->use] autorelease]];
					xmlBufferFree(buffer);
	#endif
				}

				// libxml will generate UTF-8
				[self setResponseEncoding:NSUTF8StringEncoding];
			}

			xmlFreeDoc(doc);
			doc = nil;

			[requestsUsingXMLParser removeObject:self];
			if (![requestsUsingXMLParser count]) {
				xmlCleanupParser();
			}
			[xmlParsingLock unlock];
		}
	}
	if (![self parentRequest]) {
		[[self class] updateProgressIndicator:&downloadProgressDelegate withProgress:contentLength ofTotal:contentLength];
	}

	NSMutableDictionary *newHeaders = [[[self responseHeaders] mutableCopy] autorelease];
	[newHeaders removeObjectForKey:@"Content-Encoding"];
	[self setResponseHeaders:newHeaders];

	// Write the parsed content back to the cache
	if ([self urlReplacementMode] != ASIDontModifyURLs) {
		[[self downloadCache] storeResponseForRequest:self maxAge:[self secondsToCache]];
	}

	[super requestFinished];
	[super markAsFinished];
}

- (void)readResourceURLs
{
	// Create xpath evaluation context
    xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
    if(xpathCtx == NULL) {
		[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to create new XPath context",NSLocalizedDescriptionKey,nil]]];
		return;
    }

    // Evaluate xpath expression
    xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
    if(xpathObj == NULL) {
        xmlXPathFreeContext(xpathCtx); 
		[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to evaluate XPath expression!",NSLocalizedDescriptionKey,nil]]];
		return;
    }
	
	// Now loop through our matches
	xmlNodeSetPtr nodes = xpathObj->nodesetval;

    int size = (nodes) ? nodes->nodeNr : 0;
	int i;
    for(i = size - 1; i >= 0; i--) {
		assert(nodes->nodeTab[i]);
		NSString *parentName  = [NSString stringWithCString:(char *)nodes->nodeTab[i]->parent->name encoding:[self responseEncoding]];
		NSString *nodeName = [NSString stringWithCString:(char *)nodes->nodeTab[i]->name encoding:[self responseEncoding]];

		xmlChar *nodeValue = xmlNodeGetContent(nodes->nodeTab[i]);
		NSString *value = [NSString stringWithCString:(char *)nodeValue encoding:[self responseEncoding]];
		xmlFree(nodeValue);

		// Our xpath query matched all <link> elements, but we're only interested in stylesheets
		// We do the work here rather than in the xPath query because the query is case-sensitive, and we want to match on 'stylesheet', 'StyleSHEEt' etc
		if ([[parentName lowercaseString] isEqualToString:@"link"]) {
			xmlChar *relAttribute = xmlGetNoNsProp(nodes->nodeTab[i]->parent,(xmlChar *)"rel");
			if (relAttribute) {
				NSString *rel = [NSString stringWithCString:(char *)relAttribute encoding:[self responseEncoding]];
				xmlFree(relAttribute);
				if ([[rel lowercaseString] isEqualToString:@"stylesheet"]) {
					[self addURLToFetch:value];
				}
			}

		// Parse the content of <style> tags and style attributes to find external image urls or external css files
		} else if ([[nodeName lowercaseString] isEqualToString:@"style"]) {
			NSArray *externalResources = [[self class] CSSURLsFromString:value];
			for (NSString *theURL in externalResources) {
				[self addURLToFetch:theURL];
			}

		// Parse the content of <source src=""> tags (HTML 5 audio + video)
		// We explictly disable the download of files with .webm, .ogv and .ogg extensions, since it's highly likely they won't be useful to us
		} else if ([[parentName lowercaseString] isEqualToString:@"source"] || [[parentName lowercaseString] isEqualToString:@"audio"]) {
			NSString *fileExtension = [[value pathExtension] lowercaseString];
			if (![fileExtension isEqualToString:@"ogg"] && ![fileExtension isEqualToString:@"ogv"] && ![fileExtension isEqualToString:@"webm"]) {
				[self addURLToFetch:value];
			}

		// For all other elements matched by our xpath query (except hyperlinks), add the content as an external url to fetch
		} else if (![[parentName lowercaseString] isEqualToString:@"a"]) {
			[self addURLToFetch:value];
		}
		if (nodes->nodeTab[i]->type != XML_NAMESPACE_DECL) {
			nodes->nodeTab[i] = NULL;
		}
    }
	
	xmlXPathFreeObject(xpathObj);
    xmlXPathFreeContext(xpathCtx); 
}

- (void)addURLToFetch:(NSString *)newURL
{
	// Get rid of any surrounding whitespace
	newURL = [newURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	// Don't attempt to fetch data URIs
	if ([newURL length] > 4) {
		if (![[[newURL substringToIndex:5] lowercaseString] isEqualToString:@"data:"]) {
			NSURL *theURL = [NSURL URLWithString:newURL relativeToURL:[self url]];
			if (theURL) {
				if (![[self resourceList] objectForKey:newURL]) {
					[[self resourceList] setObject:[NSMutableDictionary dictionary] forKey:newURL];
				}
			}
		}
	}
}


- (void)updateResourceURLs
{
	// Create xpath evaluation context
	xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
	if(xpathCtx == NULL) {
		[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to create new XPath context",NSLocalizedDescriptionKey,nil]]];
		return;
	}

 	// Evaluate xpath expression
	xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
	if(xpathObj == NULL) {
		xmlXPathFreeContext(xpathCtx);
		[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to evaluate XPath expression!",NSLocalizedDescriptionKey,nil]]];
		return;
	}

	// Loop through all the matches, replacing urls where nescessary
	xmlNodeSetPtr nodes = xpathObj->nodesetval;
	int size = (nodes) ? nodes->nodeNr : 0;
	int i;
	for(i = size - 1; i >= 0; i--) {
		assert(nodes->nodeTab[i]);
		NSString *parentName  = [NSString stringWithCString:(char *)nodes->nodeTab[i]->parent->name encoding:[self responseEncoding]];
		NSString *nodeName  = [NSString stringWithCString:(char *)nodes->nodeTab[i]->name encoding:[self responseEncoding]];

		xmlChar *nodeValue = xmlNodeGetContent(nodes->nodeTab[i]);
		NSString *value = [NSString stringWithCString:(char *)nodeValue encoding:[self responseEncoding]];
		xmlFree(nodeValue);

		// Replace external urls in <style> tags or in style attributes
		if ([[nodeName lowercaseString] isEqualToString:@"style"]) {
			NSArray *externalResources = [[self class] CSSURLsFromString:value];
			for (NSString *theURL in externalResources) {
				if ([value rangeOfString:theURL].location != NSNotFound) {
					NSString *newURL = [self contentForExternalURL:theURL];
					if (newURL) {
						value = [value stringByReplacingOccurrencesOfString:theURL withString:newURL];
					}
				}
			}
			xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[value cStringUsingEncoding:[self responseEncoding]]);

		// Replace relative hyperlinks with absolute ones, since we will need to set a local baseURL when loading this in a web view
		} else if ([self urlReplacementMode] == ASIReplaceExternalResourcesWithLocalURLs && [[parentName lowercaseString] isEqualToString:@"a"]) {
			NSString *newURL = [[NSURL URLWithString:value relativeToURL:[self url]] absoluteString];
			if (newURL) {
				xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[newURL cStringUsingEncoding:[self responseEncoding]]);
			}

		// Replace all other external resource urls
		} else {
			NSString *newURL = [self contentForExternalURL:value];
			if (newURL) {
				xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[newURL cStringUsingEncoding:[self responseEncoding]]);
			}
		}

		if (nodes->nodeTab[i]->type != XML_NAMESPACE_DECL) {
			nodes->nodeTab[i] = NULL;
		}
	}
	xmlXPathFreeObject(xpathObj);
	xmlXPathFreeContext(xpathCtx);
}

// The three methods below are responsible for forwarding delegate methods we want to handle to the parent request's approdiate delegate
// Certain delegate methods are ignored (eg setProgress: / setDoubleValue: / setMaxValue:)
- (BOOL)respondsToSelector:(SEL)selector
{
	if ([self parentRequest]) {
		return [[self parentRequest] respondsToSelector:selector];
	}
	//Ok, now check for selectors we want to pass on to the delegate
	if (selector == @selector(requestStarted:) || selector == @selector(request:didReceiveResponseHeaders:) || selector == @selector(request:willRedirectToURL:) || selector == @selector(requestFinished:) || selector == @selector(requestFailed:) || selector == @selector(request:didReceiveData:) || selector == @selector(authenticationNeededForRequest:) || selector == @selector(proxyAuthenticationNeededForRequest:)) {
		return [delegate respondsToSelector:selector];
	} else if (selector == @selector(request:didReceiveBytes:) || selector == @selector(request:incrementDownloadSizeBy:)) {
		return [downloadProgressDelegate respondsToSelector:selector];
	} else if (selector == @selector(request:didSendBytes:)  || selector == @selector(request:incrementUploadSizeBy:)) {
		return [uploadProgressDelegate respondsToSelector:selector];
	}
	return [super respondsToSelector:selector];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
	if ([self parentRequest]) {
		return [[self parentRequest] methodSignatureForSelector:selector];
	}
	if (selector == @selector(requestStarted:) || selector == @selector(request:didReceiveResponseHeaders:) || selector == @selector(request:willRedirectToURL:) || selector == @selector(requestFinished:) || selector == @selector(requestFailed:) || selector == @selector(request:didReceiveData:) || selector == @selector(authenticationNeededForRequest:) || selector == @selector(proxyAuthenticationNeededForRequest:)) {
		return [(id)delegate methodSignatureForSelector:selector];
	} else if (selector == @selector(request:didReceiveBytes:) || selector == @selector(request:incrementDownloadSizeBy:)) {
		return [(id)downloadProgressDelegate methodSignatureForSelector:selector];
	} else if (selector == @selector(request:didSendBytes:)  || selector == @selector(request:incrementUploadSizeBy:)) {
		return [(id)uploadProgressDelegate methodSignatureForSelector:selector];
	}
	return nil;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
	if ([self parentRequest]) {
		return [[self parentRequest] forwardInvocation:anInvocation];
	}
	SEL selector = [anInvocation selector];
	if (selector == @selector(requestStarted:) || selector == @selector(request:didReceiveResponseHeaders:) || selector == @selector(request:willRedirectToURL:) || selector == @selector(requestFinished:) || selector == @selector(requestFailed:) || selector == @selector(request:didReceiveData:) || selector == @selector(authenticationNeededForRequest:) || selector == @selector(proxyAuthenticationNeededForRequest:)) {
		[anInvocation invokeWithTarget:delegate];
	} else if (selector == @selector(request:didReceiveBytes:) || selector == @selector(request:incrementDownloadSizeBy:)) {
		[anInvocation invokeWithTarget:downloadProgressDelegate];
	} else if (selector == @selector(request:didSendBytes:)  || selector == @selector(request:incrementUploadSizeBy:)) {
		[anInvocation invokeWithTarget:uploadProgressDelegate];
	}
}

// A quick and dirty way to build a list of external resource urls from a css string
+ (NSArray *)CSSURLsFromString:(NSString *)string
{
	NSMutableArray *urls = [NSMutableArray array];
	NSScanner *scanner = [NSScanner scannerWithString:string];
	[scanner setCaseSensitive:NO];
	while (1) {
		NSString *theURL = nil;
		[scanner scanUpToString:@"url(" intoString:NULL];
		[scanner scanString:@"url(" intoString:NULL];
		[scanner scanUpToString:@")" intoString:&theURL];
		if (!theURL) {
			break;
		}
		// Remove any quotes or whitespace around the url
		theURL = [theURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		theURL = [theURL stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\"'"]];
		theURL = [theURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		[urls addObject:theURL];
	}
	return urls;
}

// Returns a relative file path from sourcePath to destinationPath (eg ../../foo/bar.txt)
- (NSString *)relativePathTo:(NSString *)destinationPath fromPath:(NSString *)sourcePath
{
	NSArray *sourcePathComponents = [sourcePath pathComponents];
	NSArray *destinationPathComponents = [destinationPath pathComponents];
	NSUInteger i;
	NSString *newPath = @"";
	NSString *sourcePathComponent, *destinationPathComponent;
	for (i=0; i<[sourcePathComponents count]; i++) {
		sourcePathComponent = [sourcePathComponents objectAtIndex:i];
		if ([destinationPathComponents count] > i) {
			destinationPathComponent = [destinationPathComponents objectAtIndex:i];
			if (![sourcePathComponent isEqualToString:destinationPathComponent]) {
				NSUInteger i2;
				for (i2=i+1; i2<[sourcePathComponents count]; i2++) {
					newPath = [newPath stringByAppendingPathComponent:@".."];
				}
				newPath = [newPath stringByAppendingPathComponent:destinationPathComponent];
				for (i2=i+1; i2<[destinationPathComponents count]; i2++) {
					newPath = [newPath stringByAppendingPathComponent:[destinationPathComponents objectAtIndex:i2]];
				}
				break;
			}
		}
	}
	return newPath;
}

- (NSString *)contentForExternalURL:(NSString *)theURL
{
	if ([self urlReplacementMode] == ASIReplaceExternalResourcesWithLocalURLs) {
		NSString *resourcePath = [[resourceList objectForKey:theURL] objectForKey:@"DataPath"];
		return [self relativePathTo:resourcePath fromPath:[self downloadDestinationPath]];
	}
	NSData *data;
	if ([[resourceList objectForKey:theURL] objectForKey:@"DataPath"]) {
		data = [NSData dataWithContentsOfFile:[[resourceList objectForKey:theURL] objectForKey:@"DataPath"]];
	} else {
		data = [[resourceList objectForKey:theURL] objectForKey:@"Data"];
	}
	NSString *contentType = [[resourceList objectForKey:theURL] objectForKey:@"ContentType"];
	if (data && contentType) {
		NSString *dataURI = [NSString stringWithFormat:@"data:%@;base64,",contentType];
		dataURI = [dataURI stringByAppendingString:[ASIHTTPRequest base64forData:data]];
		return dataURI;
	}
	return nil;
}

- (NSString *)cachePathForRequest:(ASIWebPageRequest *)theRequest
{
	// If we're using a download cache (and its a good idea to do so when using ASIWebPageRequest), ask it for the location to store this file
	// This ends up being quite efficient, as we download directly to the cache
	if ([self downloadCache]) {
		return [[self downloadCache] pathToStoreCachedResponseDataForRequest:theRequest];

	// This is a fallback for when we don't have a download cache - we store the external resource in a file in the temporary directory
	} else {
		// Borrowed from: http://stackoverflow.com/questions/652300/using-md5-hash-on-a-string-in-cocoa
		const char *cStr = [[[theRequest url] absoluteString] UTF8String];
		unsigned char result[16];
		CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
		NSString *md5 = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]]; 	
		return [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[md5 stringByAppendingPathExtension:@"html"]];
	}
}


@synthesize externalResourceQueue;
@synthesize resourceList;
@synthesize parentRequest;
@synthesize urlReplacementMode;
@end