Revision cc176feb

b/asi-http-request-with-pithos/.gitattributes
1
*.pbxproj -crlf -diff -merge
b/asi-http-request-with-pithos/.gitignore
10 10
*.pbxuser
11 11
*.mode1v3
12 12
External/GHUnit/*
13
.svn
b/asi-http-request-with-pithos/Classes/ASIAuthenticationDialog.m
133 133
{
134 134
	[self showTitle];
135 135
	
136
	UIInterfaceOrientation o = [[UIApplication sharedApplication] statusBarOrientation];
136
	UIInterfaceOrientation o = (UIInterfaceOrientation)[[UIApplication sharedApplication] statusBarOrientation];
137 137
	CGFloat angle = 0;
138 138
	switch (o) {
139 139
		case UIDeviceOrientationLandscapeLeft: angle = 90; break;
......
216 216

  
217 217
+ (void)dismiss
218 218
{
219
	[[sharedDialog parentViewController] dismissModalViewControllerAnimated:YES];
219
	if ([sharedDialog respondsToSelector:@selector(presentingViewController)])
220
		[[sharedDialog presentingViewController] dismissModalViewControllerAnimated:YES];
221
	else 
222
		[[sharedDialog parentViewController] dismissModalViewControllerAnimated:YES];
220 223
}
221 224

  
222 225
- (void)viewDidDisappear:(BOOL)animated
......
233 236
	if (self == sharedDialog) {
234 237
		[[self class] dismiss];
235 238
	} else {
236
		[[self parentViewController] dismissModalViewControllerAnimated:YES];
239
		if ([self respondsToSelector:@selector(presentingViewController)])
240
			[[self presentingViewController] dismissModalViewControllerAnimated:YES];
241
		else
242
			[[self parentViewController] dismissModalViewControllerAnimated:YES];
237 243
	}
238 244
}
239 245

  
b/asi-http-request-with-pithos/Classes/ASIDataCompressor.m
88 88
			[outputData increaseLengthBy:halfLength];
89 89
		}
90 90
		
91
		zStream.next_out = [outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
91
		zStream.next_out = (Bytef*)[outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
92 92
		zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready));
93 93
		status = deflate(&zStream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
94 94
		
......
184 184
		}
185 185
		
186 186
		// Write the deflated data out to the destination file
187
		[outputStream write:[outputData bytes] maxLength:[outputData length]];
187
		[outputStream write:(const uint8_t *)[outputData bytes] maxLength:[outputData length]];
188 188
		
189 189
		// Make sure nothing went wrong
190 190
		if ([inputStream streamStatus] == NSStreamEventErrorOccurred) {
191 191
			if (err) {
192
				*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed because we were unable to write to the destination data file at &@",sourcePath,destinationPath],NSLocalizedDescriptionKey,[outputStream streamError],NSUnderlyingErrorKey,nil]];
192
				*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed because we were unable to write to the destination data file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,[outputStream streamError],NSUnderlyingErrorKey,nil]];
193 193
            }
194 194
			[compressor closeStream];
195 195
			return NO;
......
212 212

  
213 213
+ (NSError *)deflateErrorWithCode:(int)code
214 214
{
215
	return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of data failed with code %hi",code],NSLocalizedDescriptionKey,nil]];
215
	return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of data failed with code %d",code],NSLocalizedDescriptionKey,nil]];
216 216
}
217 217

  
218 218
@synthesize streamReady;
b/asi-http-request-with-pithos/Classes/ASIDataDecompressor.m
85 85
			[outputData increaseLengthBy:halfLength];
86 86
		}
87 87
		
88
		zStream.next_out = [outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
88
		zStream.next_out = (Bytef*)[outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
89 89
		zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready));
90 90
		
91 91
		status = inflate(&zStream, Z_NO_FLUSH);
......
181 181
		}
182 182
		
183 183
		// Write the inflated data out to the destination file
184
		[outputStream write:[outputData bytes] maxLength:[outputData length]];
184
		[outputStream write:(Bytef*)[outputData bytes] maxLength:[outputData length]];
185 185
		
186 186
		// Make sure nothing went wrong
187 187
		if ([inputStream streamStatus] == NSStreamEventErrorOccurred) {
188 188
			if (err) {
189
				*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed because we were unable to write to the destination data file at &@",sourcePath,destinationPath],NSLocalizedDescriptionKey,[outputStream streamError],NSUnderlyingErrorKey,nil]];
189
				*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed because we were unable to write to the destination data file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,[outputStream streamError],NSUnderlyingErrorKey,nil]];
190 190
            }
191 191
			[decompressor closeStream];
192 192
			return NO;
......
211 211

  
212 212
+ (NSError *)inflateErrorWithCode:(int)code
213 213
{
214
	return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of data failed with code %hi",code],NSLocalizedDescriptionKey,nil]];
214
	return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of data failed with code %d",code],NSLocalizedDescriptionKey,nil]];
215 215
}
216 216

  
217 217
@synthesize streamReady;
b/asi-http-request-with-pithos/Classes/ASIDownloadCache.h
35 35
// A helper function that determines if the server has requested data should not be cached by looking at the request's response headers
36 36
+ (BOOL)serverAllowsResponseCachingForRequest:(ASIHTTPRequest *)request;
37 37

  
38
// A list of file extensions that we know won't be readable by a webview when accessed locally
39
// If we're asking for a path to cache a particular url and it has one of these extensions, we change it to '.html'
40
+ (NSArray *)fileExtensionsToHandleAsHTML;
41

  
38 42
@property (assign, nonatomic) ASICachePolicy defaultCachePolicy;
39 43
@property (retain, nonatomic) NSString *storagePath;
40 44
@property (retain) NSRecursiveLock *accessLock;
b/asi-http-request-with-pithos/Classes/ASIDownloadCache.m
14 14

  
15 15
static NSString *sessionCacheFolder = @"SessionStore";
16 16
static NSString *permanentCacheFolder = @"PermanentStore";
17
static NSArray *fileExtensionsToHandleAsHTML = nil;
17 18

  
18 19
@interface ASIDownloadCache ()
19 20
+ (NSString *)keyForURL:(NSURL *)url;
......
22 23

  
23 24
@implementation ASIDownloadCache
24 25

  
26
+ (void)initialize
27
{
28
	if (self == [ASIDownloadCache class]) {
29
		// Obviously this is not an exhaustive list, but hopefully these are the most commonly used and this will 'just work' for the widest range of people
30
		// I imagine many web developers probably use url rewriting anyway
31
		fileExtensionsToHandleAsHTML = [[NSArray alloc] initWithObjects:@"asp",@"aspx",@"jsp",@"php",@"rb",@"py",@"pl",@"cgi", nil];
32
	}
33
}
34

  
25 35
- (id)init
26 36
{
27 37
	self = [super init];
......
105 115

  
106 116
- (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
107 117
{
108
	NSMutableDictionary *responseHeaders = [NSMutableDictionary dictionaryWithDictionary:[request responseHeaders]];
109

  
110
	// If we weren't given a custom max-age, lets look for one in the response headers
111
	if (!maxAge) {
112
		NSString *cacheControl = [[responseHeaders objectForKey:@"Cache-Control"] lowercaseString];
113
		if (cacheControl) {
114
			NSScanner *scanner = [NSScanner scannerWithString:cacheControl];
115
			[scanner scanUpToString:@"max-age" intoString:NULL];
116
			if ([scanner scanString:@"max-age" intoString:NULL]) {
117
				[scanner scanString:@"=" intoString:NULL];
118
				[scanner scanDouble:&maxAge];
119
			}
120
		}
121
	}
122

  
123
	// RFC 2612 says max-age must override any Expires header
124
	if (maxAge) {
125
		return [[NSDate date] addTimeInterval:maxAge];
126
	} else {
127
		NSString *expires = [responseHeaders objectForKey:@"Expires"];
128
		if (expires) {
129
			return [ASIHTTPRequest dateFromRFC1123String:expires];
130
		}
131
	}
132
	return nil;
118
  return [ASIHTTPRequest expiryDateForRequest:request maxAge:maxAge];
133 119
}
134 120

  
135 121
- (void)storeResponseForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
......
183 169

  
184 170
	if ([request responseData]) {
185 171
		[[request responseData] writeToFile:dataPath atomically:NO];
186
	} else if ([request downloadDestinationPath] && ![[request downloadDestinationPath] isEqualToString:dataPath]) {
172
	} else if ([request downloadDestinationPath] && ![[request downloadDestinationPath] isEqualToString:dataPath]) {        
187 173
		NSError *error = nil;
188
		[[[[NSFileManager alloc] init] autorelease] copyItemAtPath:[request downloadDestinationPath] toPath:dataPath error:&error];
174
        NSFileManager* manager = [[NSFileManager alloc] init];
175
        if ([manager fileExistsAtPath:dataPath]) {
176
            [manager removeItemAtPath:dataPath error:&error];
177
        }
178
        [manager copyItemAtPath:[request downloadDestinationPath] toPath:dataPath error:&error];
179
        [manager release];
189 180
	}
190 181
	[[self accessLock] unlock];
191 182
}
......
212 203
{
213 204
	// Grab the file extension, if there is one. We do this so we can save the cached response with the same file extension - this is important if you want to display locally cached data in a web view 
214 205
	NSString *extension = [[url path] pathExtension];
215
	if (![extension length]) {
206

  
207
	// If the url doesn't have an extension, we'll add one so a webview can read it when locally cached
208
	// If the url has the extension of a common web scripting language, we'll change the extension on the cached path to html for the same reason
209
	if (![extension length] || [[[self class] fileExtensionsToHandleAsHTML] containsObject:[extension lowercaseString]]) {
216 210
		extension = @"html";
217 211
	}
218 212
	return [self pathToFile:[[[self class] keyForURL:url] stringByAppendingPathExtension:extension]];
219 213
}
220 214

  
215
+ (NSArray *)fileExtensionsToHandleAsHTML
216
{
217
	return fileExtensionsToHandleAsHTML;
218
}
219

  
220

  
221 221
- (NSString *)pathToCachedResponseHeadersForURL:(NSURL *)url
222 222
{
223 223
	return [self pathToFile:[[[self class] keyForURL:url] stringByAppendingPathExtension:@"cachedheaders"]];
......
262 262

  
263 263
	// Grab the file extension, if there is one. We do this so we can save the cached response with the same file extension - this is important if you want to display locally cached data in a web view 
264 264
	NSString *extension = [[[request url] path] pathExtension];
265
	if (![extension length]) {
265

  
266
	// If the url doesn't have an extension, we'll add one so a webview can read it when locally cached
267
	// If the url has the extension of a common web scripting language, we'll change the extension on the cached path to html for the same reason
268
	if (![extension length] || [[[self class] fileExtensionsToHandleAsHTML] containsObject:[extension lowercaseString]]) {
266 269
		extension = @"html";
267 270
	}
268 271
	path =  [path stringByAppendingPathComponent:[[[self class] keyForURL:[request url]] stringByAppendingPathExtension:extension]];
b/asi-http-request-with-pithos/Classes/ASIFormDataRequest.m
30 30
#pragma mark utilities
31 31
- (NSString*)encodeURL:(NSString *)string
32 32
{
33
	NSString *newString = NSMakeCollectable([(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding])) autorelease]);
33
	NSString *newString = [NSMakeCollectable(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding]))) autorelease];
34 34
	if (newString) {
35 35
		return newString;
36 36
	}
......
49 49
	self = [super initWithURL:newURL];
50 50
	[self setPostFormat:ASIURLEncodedPostFormat];
51 51
	[self setStringEncoding:NSUTF8StringEncoding];
52
        [self setRequestMethod:@"POST"];
52 53
	return self;
53 54
}
54 55

  
......
207 208
	[super buildPostBody];
208 209
	
209 210
#if DEBUG_FORM_DATA_REQUEST
210
	NSLog(@"%@",[self debugBodyString]);
211
	ASI_DEBUG_LOG(@"%@",[self debugBodyString]);
211 212
	[self setDebugBodyString:nil];
212 213
#endif
213 214
}
b/asi-http-request-with-pithos/Classes/ASIHTTPRequest.h
193 193
	NSString *password;
194 194
	
195 195
	// User-Agent for this request
196
	NSString *userAgent;
196
	NSString *userAgentString;
197 197
	
198 198
	// Domain used for NTLM authentication
199 199
	NSString *domain;
......
873 873
// And also by ASIS3Request
874 874
+ (NSString *)base64forData:(NSData *)theData;
875 875

  
876
// Returns the expiration date for the request.
877
// Calculated from the Expires response header property, unless maxAge is non-zero or
878
// there exists a non-zero max-age property in the Cache-Control response header.
879
+ (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
880

  
876 881
// Returns a date from a string in RFC1123 format
877 882
+ (NSDate *)dateFromRFC1123String:(NSString *)string;
878 883

  
......
898 903

  
899 904
@property (retain) NSString *username;
900 905
@property (retain) NSString *password;
901
@property (retain) NSString *userAgent;
906
@property (retain) NSString *userAgentString;
902 907
@property (retain) NSString *domain;
903 908

  
904 909
@property (retain) NSString *proxyUsername;
b/asi-http-request-with-pithos/Classes/ASIHTTPRequest.m
24 24
#import "ASIDataCompressor.h"
25 25

  
26 26
// Automatically set on build
27
NSString *ASIHTTPRequestVersion = @"v1.8.1-8 2011-06-05";
27
NSString *ASIHTTPRequestVersion = @"v1.8.1-61 2011-09-19";
28 28

  
29 29
static NSString *defaultUserAgent = nil;
30 30

  
......
105 105

  
106 106
// When YES, bandwidth will be automatically throttled when using WWAN (3G/Edge/GPRS)
107 107
// Wifi will not be throttled
108
static BOOL shouldThrottleBandwithForWWANOnly = NO;
108
static BOOL shouldThrottleBandwidthForWWANOnly = NO;
109 109
#endif
110 110

  
111 111
// Mediates access to the session cookies so requests
......
392 392
	[connectionInfo release];
393 393
	[requestID release];
394 394
	[dataDecompressor release];
395
	[userAgent release];
395
	[userAgentString release];
396 396

  
397 397
	#if NS_BLOCKS_AVAILABLE
398 398
	[self releaseBlocksOnMainThread];
......
460 460
		[authenticationNeededBlock release];
461 461
		authenticationNeededBlock = nil;
462 462
	}
463
	if (requestRedirectedBlock) {
464
		[blocks addObject:requestRedirectedBlock];
465
		[requestRedirectedBlock release];
466
		requestRedirectedBlock = nil;
467
	}
463 468
	[[self class] performSelectorOnMainThread:@selector(releaseBlocks:) withObject:blocks waitUntilDone:[NSThread isMainThread]];
464 469
}
465 470
// Always called on main thread
......
696 701
- (void)cancelOnRequestThread
697 702
{
698 703
	#if DEBUG_REQUEST_STATUS
699
	NSLog(@"[STATUS] Request cancelled: %@",self);
704
	ASI_DEBUG_LOG(@"[STATUS] Request cancelled: %@",self);
700 705
	#endif
701 706
    
702 707
	[[self cancelledLock] lock];
......
786 791
- (void)startSynchronous
787 792
{
788 793
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
789
	NSLog(@"[STATUS] Starting synchronous request %@",self);
794
	ASI_DEBUG_LOG(@"[STATUS] Starting synchronous request %@",self);
790 795
#endif
791 796
	[self setSynchronous:YES];
792 797
	[self setRunLoopMode:ASIHTTPRequestRunLoopMode];
......
811 816
- (void)startAsynchronous
812 817
{
813 818
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
814
	NSLog(@"[STATUS] Starting asynchronous request %@",self);
819
	ASI_DEBUG_LOG(@"[STATUS] Starting asynchronous request %@",self);
815 820
#endif
816 821
	[sharedQueue addOperation:self];
817 822
}
......
843 848
		
844 849
		#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
845 850
		if ([ASIHTTPRequest isMultitaskingSupported] && [self shouldContinueWhenAppEntersBackground]) {
846
			backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
847
				// Synchronize the cleanup call on the main thread in case
848
				// the task actually finishes at around the same time.
849
				dispatch_async(dispatch_get_main_queue(), ^{
850
					if (backgroundTask != UIBackgroundTaskInvalid)
851
					{
852
						[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
853
						backgroundTask = UIBackgroundTaskInvalid;
854
						[self cancel];
855
					}
856
				});
857
			}];
851
            if (!backgroundTask || backgroundTask == UIBackgroundTaskInvalid) {
852
                backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
853
                    // Synchronize the cleanup call on the main thread in case
854
                    // the task actually finishes at around the same time.
855
                    dispatch_async(dispatch_get_main_queue(), ^{
856
                        if (backgroundTask != UIBackgroundTaskInvalid)
857
                        {
858
                            [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
859
                            backgroundTask = UIBackgroundTaskInvalid;
860
                            [self cancel];
861
                        }
862
                    });
863
                }];
864
            }
858 865
		}
859 866
		#endif
860 867

  
......
962 969
	// Do we want to send credentials before we are asked for them?
963 970
	if (![self shouldPresentCredentialsBeforeChallenge]) {
964 971
		#if DEBUG_HTTP_AUTHENTICATION
965
		NSLog(@"[AUTH] Request %@ will not send credentials to the server until it asks for them",self);
972
		ASI_DEBUG_LOG(@"[AUTH] Request %@ will not send credentials to the server until it asks for them",self);
966 973
		#endif
967 974
		return;
968 975
	}
......
977 984
			[self addBasicAuthenticationHeaderWithUsername:[self username] andPassword:[self password]];
978 985

  
979 986
			#if DEBUG_HTTP_AUTHENTICATION
980
			NSLog(@"[AUTH] Request %@ has a username and password set, and was manually configured to use BASIC. Will send credentials without waiting for an authentication challenge",self);	
987
			ASI_DEBUG_LOG(@"[AUTH] Request %@ has a username and password set, and was manually configured to use BASIC. Will send credentials without waiting for an authentication challenge",self);	
981 988
			#endif
982 989

  
983 990
		} else {
......
996 1003
						if (CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
997 1004
							[self setAuthenticationScheme:[credentials objectForKey:@"AuthenticationScheme"]];
998 1005
							#if DEBUG_HTTP_AUTHENTICATION
999
							NSLog(@"[AUTH] Request %@ found cached credentials (%@), will reuse without waiting for an authentication challenge",self,[credentials objectForKey:@"AuthenticationScheme"]);
1006
							ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached credentials (%@), will reuse without waiting for an authentication challenge",self,[credentials objectForKey:@"AuthenticationScheme"]);
1000 1007
							#endif
1001 1008
						} else {
1002 1009
							[[self class] removeAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
1003 1010
							#if DEBUG_HTTP_AUTHENTICATION
1004
							NSLog(@"[AUTH] Failed to apply cached credentials to request %@. These will be removed from the session store, and this request will wait for an authentication challenge",self);
1011
							ASI_DEBUG_LOG(@"[AUTH] Failed to apply cached credentials to request %@. These will be removed from the session store, and this request will wait for an authentication challenge",self);
1005 1012
							#endif
1006 1013
						}
1007 1014

  
......
1011 1018
						NSDictionary *usernameAndPassword = [credentials objectForKey:@"Credentials"];
1012 1019
						[self addBasicAuthenticationHeaderWithUsername:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername] andPassword:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword]];
1013 1020
						#if DEBUG_HTTP_AUTHENTICATION
1014
						NSLog(@"[AUTH] Request %@ found cached BASIC credentials from a previous request. Will send credentials without waiting for an authentication challenge",self);
1021
						ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached BASIC credentials from a previous request. Will send credentials without waiting for an authentication challenge",self);
1015 1022
						#endif
1016 1023
					}
1017 1024
				}
......
1081 1088
	
1082 1089
	// Build and set the user agent string if the request does not already have a custom user agent specified
1083 1090
	if (![[self requestHeaders] objectForKey:@"User-Agent"]) {
1084
		NSString *userAgentString = [self userAgent];
1085
		if (!userAgentString) {
1086
			userAgentString = [ASIHTTPRequest defaultUserAgentString];
1091
		NSString *tempUserAgentString = [self userAgentString];
1092
		if (!tempUserAgentString) {
1093
			tempUserAgentString = [ASIHTTPRequest defaultUserAgentString];
1087 1094
		}
1088
		if (userAgentString) {
1089
			[self addRequestHeader:@"User-Agent" value:userAgentString];
1095
		if (tempUserAgentString) {
1096
			[self addRequestHeader:@"User-Agent" value:tempUserAgentString];
1090 1097
		}
1091 1098
	}
1092 1099
	
......
1169 1176
		} else {
1170 1177
			[self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self postBodyFilePath] request:self]];
1171 1178
		}
1172
		[self setReadStream:[(NSInputStream *)CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream]) autorelease]];
1179
		[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];    
1173 1180
    } else {
1174 1181
		
1175 1182
		// If we have a request body, we'll stream it from memory using our custom stream, so that we can measure bandwidth use and it can be bandwidth-throttled if necessary
......
1179 1186
			} else if ([self postBody]) {
1180 1187
				[self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self postBody] request:self]];
1181 1188
			}
1182
			[self setReadStream:[(NSInputStream *)CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream]) autorelease]];
1189
			[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];
1183 1190
		
1184 1191
		} else {
1185
			[self setReadStream:[(NSInputStream *)CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request) autorelease]];
1192
			[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request)) autorelease]];
1186 1193
		}
1187 1194
	}
1188 1195

  
......
1198 1205
    // Handle SSL certificate settings
1199 1206
    //
1200 1207

  
1201
    if([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {
1202

  
1203
        NSMutableDictionary *sslProperties = [NSMutableDictionary dictionaryWithCapacity:1];
1204

  
1208
    if([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {       
1209
       
1205 1210
        // Tell CFNetwork not to validate SSL certificates
1206 1211
        if (![self validatesSecureCertificate]) {
1207
            [sslProperties setObject:(NSString *)kCFBooleanFalse forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
1208
        }
1209

  
1212
            // see: http://iphonedevelopment.blogspot.com/2010/05/nsstream-tcp-and-ssl.html
1213
            
1214
            NSDictionary *sslProperties = [[NSDictionary alloc] initWithObjectsAndKeys:
1215
                                      [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
1216
                                      [NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
1217
                                      [NSNumber numberWithBool:NO],  kCFStreamSSLValidatesCertificateChain,
1218
                                      kCFNull,kCFStreamSSLPeerName,
1219
                                      nil];
1220
            
1221
            CFReadStreamSetProperty((CFReadStreamRef)[self readStream], 
1222
                                    kCFStreamPropertySSLSettings, 
1223
                                    (CFTypeRef)sslProperties);
1224
            [sslProperties release];
1225
        } 
1226
        
1210 1227
        // Tell CFNetwork to use a client certificate
1211 1228
        if (clientCertificateIdentity) {
1212

  
1229
            NSMutableDictionary *sslProperties = [NSMutableDictionary dictionaryWithCapacity:1];
1230
            
1213 1231
			NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[clientCertificates count]+1];
1214 1232

  
1215 1233
			// The first object in the array is our SecIdentityRef
......
1219 1237
			for (id cert in clientCertificates) {
1220 1238
				[certificates addObject:cert];
1221 1239
			}
1240
            
1222 1241
            [sslProperties setObject:certificates forKey:(NSString *)kCFStreamSSLCertificates];
1242
            
1243
            CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, sslProperties);
1223 1244
        }
1224

  
1225
        CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, sslProperties);
1245
        
1226 1246
    }
1227 1247

  
1228 1248
	//
......
1288 1308
			// Check if we should have expired this connection
1289 1309
			} else if ([[[self connectionInfo] objectForKey:@"expires"] timeIntervalSinceNow] < 0) {
1290 1310
				#if DEBUG_PERSISTENT_CONNECTIONS
1291
				NSLog(@"[CONNECTION] Not re-using connection #%i because it has expired",[[[self connectionInfo] objectForKey:@"id"] intValue]);
1311
				ASI_DEBUG_LOG(@"[CONNECTION] Not re-using connection #%i because it has expired",[[[self connectionInfo] objectForKey:@"id"] intValue]);
1292 1312
				#endif
1293 1313
				[persistentConnectionsPool removeObject:[self connectionInfo]];
1294 1314
				[self setConnectionInfo:nil];
......
1296 1316
			} else if ([[self connectionInfo] objectForKey:@"request"] != nil) {
1297 1317
                //Some other request reused this connection already - we'll have to create a new one
1298 1318
				#if DEBUG_PERSISTENT_CONNECTIONS
1299
                NSLog(@"%@ - Not re-using connection #%i for request #%i because it is already used by request #%i",self,[[[self connectionInfo] objectForKey:@"id"] intValue],[[self requestID] intValue],[[[self connectionInfo] objectForKey:@"request"] intValue]);
1319
                ASI_DEBUG_LOG(@"%@ - Not re-using connection #%i for request #%i because it is already used by request #%i",self,[[[self connectionInfo] objectForKey:@"id"] intValue],[[self requestID] intValue],[[[self connectionInfo] objectForKey:@"request"] intValue]);
1300 1320
				#endif
1301 1321
                [self setConnectionInfo:nil];
1302 1322
            }
......
1340 1360
		CFReadStreamSetProperty((CFReadStreamRef)[self readStream],  kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue);
1341 1361
		
1342 1362
		#if DEBUG_PERSISTENT_CONNECTIONS
1343
		NSLog(@"[CONNECTION] Request #%@ will use connection #%i",[self requestID],[[[self connectionInfo] objectForKey:@"id"] intValue]);
1363
		ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ will use connection #%i",[self requestID],[[[self connectionInfo] objectForKey:@"id"] intValue]);
1344 1364
		#endif
1345 1365
		
1346 1366
		
......
1351 1371
	
1352 1372
	} else {
1353 1373
		#if DEBUG_PERSISTENT_CONNECTIONS
1354
		NSLog(@"[CONNECTION] Request %@ will not use a persistent connection",self);
1374
		ASI_DEBUG_LOG(@"[CONNECTION] Request %@ will not use a persistent connection",self);
1355 1375
		#endif
1356 1376
	}
1357 1377
	
......
1519 1539
			[self setLastBytesSent:totalBytesSent];	
1520 1540
			
1521 1541
			// Find out how much data we've uploaded so far
1522
			[self setTotalBytesSent:[NSMakeCollectable([(NSNumber *)CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount) autorelease]) unsignedLongLongValue]];
1542
			[self setTotalBytesSent:[[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) autorelease] unsignedLongLongValue]];
1523 1543
			if (totalBytesSent > lastBytesSent) {
1524 1544
				
1525 1545
				// We've uploaded more data,  reset the timeout
......
1528 1548
						
1529 1549
				#if DEBUG_REQUEST_STATUS
1530 1550
				if ([self totalBytesSent] == [self postLength]) {
1531
					NSLog(@"[STATUS] Request %@ finished uploading data",self);
1551
					ASI_DEBUG_LOG(@"[STATUS] Request %@ finished uploading data",self);
1532 1552
				}
1533 1553
				#endif
1534 1554
			}
......
1985 2005
- (void)requestFinished
1986 2006
{
1987 2007
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
1988
	NSLog(@"[STATUS] Request finished: %@",self);
2008
	ASI_DEBUG_LOG(@"[STATUS] Request finished: %@",self);
1989 2009
#endif
1990 2010
	if ([self error] || [self mainRequest]) {
1991 2011
		return;
......
2052 2072
- (void)failWithError:(NSError *)theError
2053 2073
{
2054 2074
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
2055
	NSLog(@"[STATUS] Request %@: %@",self,(theError == ASIRequestCancelledError ? @"Cancelled" : @"Failed"));
2075
	ASI_DEBUG_LOG(@"[STATUS] Request %@: %@",self,(theError == ASIRequestCancelledError ? @"Cancelled" : @"Failed"));
2056 2076
#endif
2057 2077
	[self setComplete:YES];
2058 2078
	
......
2060 2080
	if (theError && [theError code] != ASIAuthenticationErrorType && [theError code] != ASITooMuchRedirectionErrorType) {
2061 2081
		[connectionsLock lock];
2062 2082
		#if DEBUG_PERSISTENT_CONNECTIONS
2063
		NSLog(@"[CONNECTION] Request #%@ failed and will invalidate connection #%@",[self requestID],[[self connectionInfo] objectForKey:@"id"]);
2083
		ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ failed and will invalidate connection #%@",[self requestID],[[self connectionInfo] objectForKey:@"id"]);
2064 2084
		#endif
2065 2085
		[[self connectionInfo] removeObjectForKey:@"request"];
2066 2086
		[persistentConnectionsPool removeObject:[self connectionInfo]];
......
2128 2148

  
2129 2149
	#if DEBUG_REQUEST_STATUS
2130 2150
	if ([self totalBytesSent] == [self postLength]) {
2131
		NSLog(@"[STATUS] Request %@ received response headers",self);
2151
		ASI_DEBUG_LOG(@"[STATUS] Request %@ received response headers",self);
2132 2152
	}
2133 2153
	#endif		
2134 2154

  
2135
	[self setResponseHeaders:[(NSDictionary *)CFHTTPMessageCopyAllHeaderFields(message) autorelease]];
2155
	[self setResponseHeaders:[NSMakeCollectable(CFHTTPMessageCopyAllHeaderFields(message)) autorelease]];
2136 2156
	[self setResponseStatusCode:(int)CFHTTPMessageGetResponseStatusCode(message)];
2137
	[self setResponseStatusMessage:[(NSString *)CFHTTPMessageCopyResponseStatusLine(message) autorelease]];
2157
	[self setResponseStatusMessage:[NSMakeCollectable(CFHTTPMessageCopyResponseStatusLine(message)) autorelease]];
2138 2158

  
2139 2159
	if ([self downloadCache] && ([[self downloadCache] canUseCachedDataForRequest:self])) {
2140 2160

  
......
2156 2176
	} else {
2157 2177
		#if DEBUG_HTTP_AUTHENTICATION
2158 2178
		if ([self authenticationScheme]) {
2159
			NSLog(@"[AUTH] Request %@ has passed %@ authentication",self,[self authenticationScheme]);
2179
			ASI_DEBUG_LOG(@"[AUTH] Request %@ has passed %@ authentication",self,[self authenticationScheme]);
2160 2180
		}
2161 2181
		#endif
2162 2182
	}
......
2168 2188
		if (!requestAuthentication && [[self authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic] && [self username] && [self password] && [self useSessionPersistence]) {
2169 2189

  
2170 2190
			#if DEBUG_HTTP_AUTHENTICATION
2171
			NSLog(@"[AUTH] Request %@ passed BASIC authentication, and will save credentials in the session store for future use",self);
2191
			ASI_DEBUG_LOG(@"[AUTH] Request %@ passed BASIC authentication, and will save credentials in the session store for future use",self);
2172 2192
			#endif
2173 2193
			
2174 2194
			NSMutableDictionary *newCredentials = [NSMutableDictionary dictionaryWithCapacity:2];
......
2238 2258
		
2239 2259
		NSString *connectionHeader = [[[self responseHeaders] objectForKey:@"Connection"] lowercaseString];
2240 2260

  
2241
		NSString *httpVersion = NSMakeCollectable([(NSString *)CFHTTPMessageCopyVersion(message) autorelease]);
2261
		NSString *httpVersion = [NSMakeCollectable(CFHTTPMessageCopyVersion(message)) autorelease];
2242 2262
		
2243 2263
		// Don't re-use the connection if the server is HTTP 1.0 and didn't send Connection: Keep-Alive
2244 2264
		if (![httpVersion isEqualToString:(NSString *)kCFHTTPVersion1_0] || [connectionHeader isEqualToString:@"keep-alive"]) {
......
2262 2282
						[self setConnectionCanBeReused:YES];
2263 2283
						[self setPersistentConnectionTimeoutSeconds:timeout];
2264 2284
						#if DEBUG_PERSISTENT_CONNECTIONS
2265
							NSLog(@"[CONNECTION] Got a keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
2285
							ASI_DEBUG_LOG(@"[CONNECTION] Got a keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
2266 2286
						#endif					
2267 2287
					}
2268 2288
				
......
2270 2290
				} else {
2271 2291
					[self setConnectionCanBeReused:YES];
2272 2292
					#if DEBUG_PERSISTENT_CONNECTIONS
2273
						NSLog(@"[CONNECTION] Got no keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
2293
						ASI_DEBUG_LOG(@"[CONNECTION] Got no keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
2274 2294
					#endif
2275 2295
				}
2276 2296
			}
......
2334 2354
	[self setRequestCookies:[NSMutableArray array]];
2335 2355

  
2336 2356
	#if DEBUG_REQUEST_STATUS
2337
	NSLog(@"[STATUS] Request will redirect (code: %i): %@",responseCode,self);
2357
	ASI_DEBUG_LOG(@"[STATUS] Request will redirect (code: %i): %@",responseCode,self);
2338 2358
	#endif
2339 2359

  
2340 2360
	return YES;
......
2523 2543
	if (user && pass) {
2524 2544

  
2525 2545
		#if DEBUG_HTTP_AUTHENTICATION
2526
		NSLog(@"[AUTH] Request %@ will use credentials set on its url",self);
2546
		ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials set on its url",self);
2527 2547
		#endif
2528 2548

  
2529 2549
	} else {
......
2534 2554
			pass = [[self mainRequest] password];
2535 2555

  
2536 2556
			#if DEBUG_HTTP_AUTHENTICATION
2537
			NSLog(@"[AUTH] Request %@ will use credentials from its parent request",self);
2557
			ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from its parent request",self);
2538 2558
			#endif
2539 2559

  
2540 2560
		// Let's try to use the ones set in this object
......
2543 2563
			pass = [self password];
2544 2564

  
2545 2565
			#if DEBUG_HTTP_AUTHENTICATION
2546
			NSLog(@"[AUTH] Request %@ will use username and password properties as credentials",self);
2566
			ASI_DEBUG_LOG(@"[AUTH] Request %@ will use username and password properties as credentials",self);
2547 2567
			#endif
2548 2568
		}		
2549 2569
	}
......
2556 2576
			pass = [authenticationCredentials password];
2557 2577
			#if DEBUG_HTTP_AUTHENTICATION
2558 2578
			if (user && pass) {
2559
				NSLog(@"[AUTH] Request %@ will use credentials from the keychain",self);
2579
				ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from the keychain",self);
2560 2580
			}
2561 2581
			#endif
2562 2582
		}
......
2592 2612
- (void)retryUsingSuppliedCredentials
2593 2613
{
2594 2614
	#if DEBUG_HTTP_AUTHENTICATION
2595
		NSLog(@"[AUTH] Request %@ received credentials from its delegate or an ASIAuthenticationDialog, will retry",self);
2615
		ASI_DEBUG_LOG(@"[AUTH] Request %@ received credentials from its delegate or an ASIAuthenticationDialog, will retry",self);
2596 2616
	#endif
2597 2617
	//If the url was changed by the delegate, our CFHTTPMessageRef will be NULL and we'll go back to the start
2598 2618
	if (!request) {
......
2606 2626
- (void)cancelAuthentication
2607 2627
{
2608 2628
	#if DEBUG_HTTP_AUTHENTICATION
2609
		NSLog(@"[AUTH] Request %@ had authentication cancelled by its delegate or an ASIAuthenticationDialog",self);
2629
		ASI_DEBUG_LOG(@"[AUTH] Request %@ had authentication cancelled by its delegate or an ASIAuthenticationDialog",self);
2610 2630
	#endif
2611 2631
	[self performSelector:@selector(failAuthentication) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
2612 2632
}
......
2749 2769
		CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
2750 2770
		proxyAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
2751 2771
		CFRelease(responseHeader);
2752
		[self setProxyAuthenticationScheme:[(NSString *)CFHTTPAuthenticationCopyMethod(proxyAuthentication) autorelease]];
2772
		[self setProxyAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(proxyAuthentication)) autorelease]];
2753 2773
	}
2754 2774
	
2755 2775
	// If we haven't got a CFHTTPAuthenticationRef by now, something is badly wrong, so we'll have to give up
......
2762 2782
	// Get the authentication realm
2763 2783
	[self setProxyAuthenticationRealm:nil];
2764 2784
	if (!CFHTTPAuthenticationRequiresAccountDomain(proxyAuthentication)) {
2765
		[self setProxyAuthenticationRealm:[(NSString *)CFHTTPAuthenticationCopyRealm(proxyAuthentication) autorelease]];
2785
		[self setProxyAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(proxyAuthentication)) autorelease]];
2766 2786
	}
2767 2787
	
2768 2788
	// See if authentication is valid
......
2926 2946
		CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
2927 2947
		requestAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
2928 2948
		CFRelease(responseHeader);
2929
		[self setAuthenticationScheme:[(NSString *)CFHTTPAuthenticationCopyMethod(requestAuthentication) autorelease]];
2949
		[self setAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(requestAuthentication)) autorelease]];
2930 2950
	}
2931 2951
	
2932 2952
	if (!requestAuthentication) {
2933 2953
		#if DEBUG_HTTP_AUTHENTICATION
2934
		NSLog(@"[AUTH] Request %@ failed to read authentication information from response headers",self);
2954
		ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to read authentication information from response headers",self);
2935 2955
		#endif
2936 2956

  
2937 2957
		[self cancelLoad];
......
2942 2962
	// Get the authentication realm
2943 2963
	[self setAuthenticationRealm:nil];
2944 2964
	if (!CFHTTPAuthenticationRequiresAccountDomain(requestAuthentication)) {
2945
		[self setAuthenticationRealm:[(NSString *)CFHTTPAuthenticationCopyRealm(requestAuthentication) autorelease]];
2965
		[self setAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(requestAuthentication)) autorelease]];
2946 2966
	}
2947 2967
	
2948 2968
	#if DEBUG_HTTP_AUTHENTICATION
......
2953 2973
			realm = @"";
2954 2974
		}
2955 2975
		if ([self authenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM || [self authenticationRetryCount] == 0) {
2956
			NSLog(@"[AUTH] Request %@ received 401 challenge and must authenticate using %@%@",self,[self authenticationScheme],realm);
2976
			ASI_DEBUG_LOG(@"[AUTH] Request %@ received 401 challenge and must authenticate using %@%@",self,[self authenticationScheme],realm);
2957 2977
		} else {
2958
			NSLog(@"[AUTH] Request %@ NTLM handshake step %i",self,[self authenticationRetryCount]+1);
2978
			ASI_DEBUG_LOG(@"[AUTH] Request %@ NTLM handshake step %i",self,[self authenticationRetryCount]+1);
2959 2979
		}
2960 2980
	#endif
2961 2981

  
......
2970 2990
		if (err.domain == kCFStreamErrorDomainHTTP && (err.error == kCFStreamErrorHTTPAuthenticationBadUserName || err.error == kCFStreamErrorHTTPAuthenticationBadPassword)) {
2971 2991

  
2972 2992
			#if DEBUG_HTTP_AUTHENTICATION
2973
			NSLog(@"[AUTH] Request %@ had bad credentials, will remove them from the session store if they are cached",self);
2993
			ASI_DEBUG_LOG(@"[AUTH] Request %@ had bad credentials, will remove them from the session store if they are cached",self);
2974 2994
			#endif
2975 2995

  
2976 2996
			// Prevent more than one request from asking for credentials at once
......
2984 3004
			if ([self error] || [self isCancelled]) {
2985 3005

  
2986 3006
				#if DEBUG_HTTP_AUTHENTICATION
2987
				NSLog(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
3007
				ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
2988 3008
				#endif
2989 3009

  
2990 3010
				[delegateAuthenticationLock unlock];
......
2997 3017
				if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
2998 3018

  
2999 3019
					#if DEBUG_HTTP_AUTHENTICATION
3000
					NSLog(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
3020
					ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
3001 3021
					#endif
3002 3022

  
3003 3023
					[delegateAuthenticationLock unlock];
......
3011 3031
			if ([self willAskDelegateForCredentials]) {
3012 3032

  
3013 3033
				#if DEBUG_HTTP_AUTHENTICATION
3014
				NSLog(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
3034
				ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
3015 3035
				#endif
3016 3036

  
3017 3037
				[delegateAuthenticationLock unlock];
......
3020 3040
			if ([self showAuthenticationDialog]) {
3021 3041

  
3022 3042
				#if DEBUG_HTTP_AUTHENTICATION
3023
				NSLog(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
3043
				ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
3024 3044
				#endif
3025 3045

  
3026 3046
				[delegateAuthenticationLock unlock];
......
3030 3050
		}
3031 3051

  
3032 3052
		#if DEBUG_HTTP_AUTHENTICATION
3033
		NSLog(@"[AUTH] Request %@ has no credentials to present and must give up",self);
3053
		ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
3034 3054
		#endif
3035 3055

  
3036 3056
		[self cancelLoad];
......
3048 3068
			// We've failed NTLM authentication twice, we should assume our credentials are wrong
3049 3069
		} else if ([self authenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM && [self authenticationRetryCount ] == 2) {
3050 3070
			#if DEBUG_HTTP_AUTHENTICATION
3051
			NSLog(@"[AUTH] Request %@ has failed NTLM authentication",self);
3071
			ASI_DEBUG_LOG(@"[AUTH] Request %@ has failed NTLM authentication",self);
3052 3072
			#endif
3053 3073

  
3054 3074
			[self failWithError:ASIAuthenticationError];
......
3056 3076
		} else {
3057 3077

  
3058 3078
			#if DEBUG_HTTP_AUTHENTICATION
3059
			NSLog(@"[AUTH] Request %@ had credentials and they were not marked as bad, but we got a 401 all the same.",self);
3079
			ASI_DEBUG_LOG(@"[AUTH] Request %@ had credentials and they were not marked as bad, but we got a 401 all the same.",self);
3060 3080
			#endif
3061 3081

  
3062 3082
			[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
......
3072 3092
		if ([self error] || [self isCancelled]) {
3073 3093

  
3074 3094
			#if DEBUG_HTTP_AUTHENTICATION
3075
			NSLog(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
3095
			ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
3076 3096
			#endif
3077 3097

  
3078 3098
			[delegateAuthenticationLock unlock];
......
3085 3105
			if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
3086 3106

  
3087 3107
				#if DEBUG_HTTP_AUTHENTICATION
3088
				NSLog(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
3108
				ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
3089 3109
				#endif
3090 3110

  
3091 3111
				[delegateAuthenticationLock unlock];
......
3105 3125
				[self startRequest];
3106 3126
			} else {
3107 3127
				#if DEBUG_HTTP_AUTHENTICATION
3108
				NSLog(@"[AUTH] Request %@ failed to apply credentials",self);
3128
				ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to apply credentials",self);
3109 3129
				#endif
3110 3130
				[delegateAuthenticationLock unlock];
3111 3131
				[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
......
3115 3135
		if ([self willAskDelegateForCredentials]) {
3116 3136

  
3117 3137
			#if DEBUG_HTTP_AUTHENTICATION
3118
			NSLog(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
3138
			ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
3119 3139
			#endif
3120 3140

  
3121 3141
			[delegateAuthenticationLock unlock];
......
3124 3144
		if ([self showAuthenticationDialog]) {
3125 3145

  
3126 3146
			#if DEBUG_HTTP_AUTHENTICATION
3127
			NSLog(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
3147
			ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
3128 3148
			#endif
3129 3149

  
3130 3150
			[delegateAuthenticationLock unlock];
......
3132 3152
		}
3133 3153

  
3134 3154
		#if DEBUG_HTTP_AUTHENTICATION
3135
		NSLog(@"[AUTH] Request %@ has no credentials to present and must give up",self);
3155
		ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
3136 3156
		#endif
3137 3157
		[delegateAuthenticationLock unlock];
3138 3158
		[self failWithError:ASIAuthenticationError];
......
3159 3179
	
3160 3180
	if ([self complete] || [self isCancelled]) {
3161 3181
		[[self cancelledLock] unlock];
3162
		[pool release];
3182
		[pool drain];
3163 3183
		return;
3164 3184
	}
3165 3185

  
......
3196 3216
	}
3197 3217

  
3198 3218
	CFRelease(self);
3199
	[pool release];
3219
	[pool drain];
3200 3220
}
3201 3221

  
3202 3222
- (BOOL)willAskDelegateToConfirmRedirect
......
3373 3393
{	
3374 3394

  
3375 3395
#if DEBUG_REQUEST_STATUS
3376
	NSLog(@"[STATUS] Request %@ finished downloading data (%qu bytes)",self, [self totalBytesRead]);
3396
	ASI_DEBUG_LOG(@"[STATUS] Request %@ finished downloading data (%qu bytes)",self, [self totalBytesRead]);
3377 3397
#endif
3378 3398
	[self setStatusTimer:nil];
3379 3399
	[self setDownloadComplete:YES];
......
3385 3405
	[progressLock lock];	
3386 3406
	// Find out how much data we've uploaded so far
3387 3407
	[self setLastBytesSent:totalBytesSent];	
3388
	[self setTotalBytesSent:[NSMakeCollectable([(NSNumber *)CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount) autorelease]) unsignedLongLongValue]];
3408
	[self setTotalBytesSent:[[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) autorelease] unsignedLongLongValue]];
3389 3409
	[self setComplete:YES];
3390 3410
	if (![self contentLength]) {
3391 3411
		[self setContentLength:[self totalBytesRead]];
......
3471 3491
	}
3472 3492
	#if DEBUG_PERSISTENT_CONNECTIONS
3473 3493
	if ([self requestID]) {
3474
		NSLog(@"[CONNECTION] Request #%@ finished using connection #%@",[self requestID], [[self connectionInfo] objectForKey:@"id"]);
3494
		ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ finished using connection #%@",[self requestID], [[self connectionInfo] objectForKey:@"id"]);
3475 3495
	}
3476 3496
	#endif
3477 3497
	[[self connectionInfo] removeObjectForKey:@"request"];
......
3495 3515
		
3496 3516
	// If request has asked delegate or ASIAuthenticationDialog for credentials
3497 3517
	} else if ([self authenticationNeeded]) {
3498
		CFRunLoopStop(CFRunLoopGetCurrent());
3518
        // Do nothing.
3499 3519
	}
3500 3520

  
3501 3521
}
......
3507 3527

  
3508 3528
	// dealloc won't be called when running with GC, so we'll clean these up now
3509 3529
	if (request) {
3510
		CFMakeCollectable(request);
3530
		CFRelease(request);
3531
		request = nil;
3511 3532
	}
3512 3533
	if (requestAuthentication) {
3513
		CFMakeCollectable(requestAuthentication);
3534
		CFRelease(requestAuthentication);
3535
		requestAuthentication = nil;
3514 3536
	}
3515 3537
	if (proxyAuthentication) {
3516
		CFMakeCollectable(proxyAuthentication);
3538
		CFRelease(proxyAuthentication);
3539
		proxyAuthentication = nil;
3517 3540
	}
3518 3541

  
3519 3542
    BOOL wasInProgress = inProgress;
......
3532 3555
    if (!wasFinished)
3533 3556
        [self didChangeValueForKey:@"isFinished"];
3534 3557

  
3535
	CFRunLoopStop(CFRunLoopGetCurrent());
3536

  
3537 3558
	#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
3538 3559
	if ([ASIHTTPRequest isMultitaskingSupported] && [self shouldContinueWhenAppEntersBackground]) {
3539 3560
		dispatch_async(dispatch_get_main_queue(), ^{
......
3609 3630
		[self setWillRetryRequest:NO];
3610 3631

  
3611 3632
		#if DEBUG_PERSISTENT_CONNECTIONS
3612
			NSLog(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - will retry with a new connection", [[self connectionInfo] objectForKey:@"id"]);
3633
			ASI_DEBUG_LOG(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - will retry with a new connection", [[self connectionInfo] objectForKey:@"id"]);
3613 3634
		#endif
3614 3635
		[connectionsLock lock];
3615 3636
		[[self connectionInfo] removeObjectForKey:@"request"];
......
3621 3642
		return YES;
3622 3643
	}
3623 3644
	#if DEBUG_PERSISTENT_CONNECTIONS
3624
		NSLog(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - we have already retried with a new connection, so we must give up", [[self connectionInfo] objectForKey:@"id"]);
3645
		ASI_DEBUG_LOG(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - we have already retried with a new connection, so we must give up", [[self connectionInfo] objectForKey:@"id"]);
3625 3646
	#endif	
3626 3647
	return NO;
3627 3648
}
......
3629 3650
- (void)handleStreamError
3630 3651

  
3631 3652
{
3632
	NSError *underlyingError = NSMakeCollectable([(NSError *)CFReadStreamCopyError((CFReadStreamRef)[self readStream]) autorelease]);
3653
	NSError *underlyingError = [NSMakeCollectable(CFReadStreamCopyError((CFReadStreamRef)[self readStream])) autorelease];
3633 3654

  
3634 3655
	if (![self error]) { // We may already have handled this error
3635 3656
		
......
3807 3828
		} else {
3808 3829

  
3809 3830
#if TARGET_OS_IPHONE
3810
			NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)CFNetworkCopySystemProxySettings() autorelease]);
3831
			NSDictionary *proxySettings = [NSMakeCollectable(CFNetworkCopySystemProxySettings()) autorelease];
3811 3832
#else
3812
			NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)SCDynamicStoreCopyProxies(NULL) autorelease]);
3833
			NSDictionary *proxySettings = [NSMakeCollectable(SCDynamicStoreCopyProxies(NULL)) autorelease];
3813 3834
#endif
3814 3835

  
3815
			proxies = NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings) autorelease]);
3836
			proxies = [NSMakeCollectable(CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings)) autorelease];
3816 3837

  
3817 3838
			// Now check to see if the proxy settings contained a PAC url, we need to run the script to get the real list of proxies if so
3818 3839
			NSDictionary *settings = [proxies objectAtIndex:0];
......
3964 3985

  
3965 3986
		// Obtain the list of proxies by running the autoconfiguration script
3966 3987
		CFErrorRef err = NULL;
3967
		NSArray *proxies = NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef)script,(CFURLRef)[self url], &err) autorelease]);
3988
		NSArray *proxies = [NSMakeCollectable(CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef)script,(CFURLRef)[self url], &err)) autorelease];
3968 3989
		if (!err && [proxies count] > 0) {
3969 3990
			NSDictionary *settings = [proxies objectAtIndex:0];
3970 3991
			[self setProxyHost:[settings objectForKey:(NSString *)kCFProxyHostNameKey]];
......
4009 4030
		NSDictionary *existingConnection = [persistentConnectionsPool objectAtIndex:i];
4010 4031
		if (![existingConnection objectForKey:@"request"] && [[existingConnection objectForKey:@"expires"] timeIntervalSinceNow] <= 0) {
4011 4032
#if DEBUG_PERSISTENT_CONNECTIONS
4012
			NSLog(@"[CONNECTION] Closing connection #%i because it has expired",[[existingConnection objectForKey:@"id"] intValue]);
4033
			ASI_DEBUG_LOG(@"[CONNECTION] Closing connection #%i because it has expired",[[existingConnection objectForKey:@"id"] intValue]);
4013 4034
#endif
4014 4035
			NSInputStream *stream = [existingConnection objectForKey:@"stream"];
4015 4036
			if (stream) {
......
4023 4044
}
4024 4045

  
4025 4046
#pragma mark NSCopying
4026

  
4027 4047
- (id)copyWithZone:(NSZone *)zone
4028 4048
{
4029 4049
	// Don't forget - this will return a retained copy!
......
4078 4098
	[newRequest setShouldUseRFC2616RedirectBehaviour:[self shouldUseRFC2616RedirectBehaviour]];
4079 4099
	[newRequest setShouldAttemptPersistentConnection:[self shouldAttemptPersistentConnection]];
4080 4100
	[newRequest setPersistentConnectionTimeoutSeconds:[self persistentConnectionTimeoutSeconds]];
4101
    [newRequest setAuthenticationScheme:[self authenticationScheme]];
4081 4102
	return newRequest;
4082 4103
}
4083 4104

  
......
4232 4253
		if ([self username] && [self password]) {
4233 4254
			NSDictionary *usernameAndPassword = [theCredentials objectForKey:@"Credentials"];
4234 4255
			NSString *storedUsername = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername];
4235
			NSString *storedPassword = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername];
4256
			NSString *storedPassword = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword];
4236 4257
			if (![storedUsername isEqualToString:[self username]] || ![storedPassword isEqualToString:[self password]]) {
4237 4258
				continue;
4238 4259
			}
......
4417 4438
		}
4418 4439
		return [[defaultUserAgent retain] autorelease];
4419 4440
	}
4441
	return nil;
4420 4442
}
4421 4443

  
4422 4444
+ (void)setDefaultUserAgentString:(NSString *)agent
......
4445 4467
	if (!MIMEType) {
4446 4468
		return @"application/octet-stream";
4447 4469
	}
4448
    return NSMakeCollectable([(NSString *)MIMEType autorelease]);
4470
    return [NSMakeCollectable(MIMEType) autorelease];
4449 4471
}
4450 4472

  
4451 4473
#pragma mark bandwidth measurement / throttling
......
4464 4486
				if ([self readStreamIsScheduled]) {
4465 4487
					[self unscheduleReadStream];
4466 4488
					#if DEBUG_THROTTLING
4467
					NSLog(@"[THROTTLING] Sleeping request %@ until after %@",self,throttleWakeUpTime);
4489
					ASI_DEBUG_LOG(@"[THROTTLING] Sleeping request %@ until after %@",self,throttleWakeUpTime);
4468 4490
					#endif
4469 4491
				}
4470 4492
			} else {
4471 4493
				if (![self readStreamIsScheduled]) {
4472 4494
					[self scheduleReadStream];
4473 4495
					#if DEBUG_THROTTLING
4474
					NSLog(@"[THROTTLING] Waking up request %@",self);
4496
					ASI_DEBUG_LOG(@"[THROTTLING] Waking up request %@",self);
4475 4497
					#endif
4476 4498
				}
4477 4499
			}
......
4489 4511
#if TARGET_OS_IPHONE
4490 4512
	[bandwidthThrottlingLock lock];
4491 4513

  
4492
	BOOL throttle = isBandwidthThrottled || (!shouldThrottleBandwithForWWANOnly && (maxBandwidthPerSecond > 0));
4514
	BOOL throttle = isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond > 0));
4493 4515
	[bandwidthThrottlingLock unlock];
4494 4516
	return throttle;
4495 4517
#else
......
4534 4556
		}
4535 4557
	}
4536 4558
	#if DEBUG_THROTTLING
4537
	NSLog(@"[THROTTLING] ===Used: %u bytes of bandwidth in last measurement period===",bandwidthUsedInLastSecond);
4559
	ASI_DEBUG_LOG(@"[THROTTLING] ===Used: %u bytes of bandwidth in last measurement period===",bandwidthUsedInLastSecond);
4538 4560
	#endif
4539 4561
	[bandwidthUsageTracker addObject:[NSNumber numberWithUnsignedLong:bandwidthUsedInLastSecond]];
4540 4562
	[bandwidthMeasurementDate release];
......
4569 4591
	// Are we performing bandwidth throttling?
4570 4592
	if (
4571 4593
	#if TARGET_OS_IPHONE
4572
	isBandwidthThrottled || (!shouldThrottleBandwithForWWANOnly && (maxBandwidthPerSecond))
4594
	isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond))
4573 4595
	#else
4574 4596
	maxBandwidthPerSecond
4575 4597
	#endif
......
4621 4643
		[ASIHTTPRequest setMaxBandwidthPerSecond:0];
4622 4644
		[bandwidthThrottlingLock lock];
4623 4645
		isBandwidthThrottled = NO;
4624
		shouldThrottleBandwithForWWANOnly = NO;
4646
		shouldThrottleBandwidthForWWANOnly = NO;
4625 4647
		[bandwidthThrottlingLock unlock];
4626 4648
	}
4627 4649
}
......
4629 4651
+ (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit
4630 4652
{	
4631 4653
	[bandwidthThrottlingLock lock];
4632
	shouldThrottleBandwithForWWANOnly = YES;
4654
	shouldThrottleBandwidthForWWANOnly = YES;
4633 4655
	maxBandwidthPerSecond = limit;
4634 4656
	[ASIHTTPRequest registerForNetworkReachabilityNotifications];	
4635 4657
	[bandwidthThrottlingLock unlock];
......
4687 4709
    @synchronized(self) {
4688 4710
        return [[defaultCache retain] autorelease];
4689 4711
    }
4712
	return nil;
4690 4713
}
4691 4714

  
4692 4715

  
......
4770 4793
    BOOL runAlways = YES; // Introduced to cheat Static Analyzer
4771 4794
	while (runAlways) {
4772 4795
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4773
		CFRunLoopRun();
4774
		[pool release];
4796
        CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, true);
4797
		[pool drain];
4775 4798
	}
4776 4799

  
4777 4800
	// Should never be called, but anyway
......
4824 4847
    return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
4825 4848
}
4826 4849

  
4850
+ (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
4851
{
4852
	NSDictionary *responseHeaders = [request responseHeaders];
4853
  
4854
	// If we weren't given a custom max-age, lets look for one in the response headers
4855
	if (!maxAge) {
4856
		NSString *cacheControl = [[responseHeaders objectForKey:@"Cache-Control"] lowercaseString];
4857
		if (cacheControl) {
4858
			NSScanner *scanner = [NSScanner scannerWithString:cacheControl];
4859
			[scanner scanUpToString:@"max-age" intoString:NULL];
4860
			if ([scanner scanString:@"max-age" intoString:NULL]) {
4861
				[scanner scanString:@"=" intoString:NULL];
4862
				[scanner scanDouble:&maxAge];
4863
			}
4864
		}
4865
	}
4866
  
4867
	// RFC 2612 says max-age must override any Expires header
4868
	if (maxAge) {
4869
		return [[NSDate date] addTimeInterval:maxAge];
4870
	} else {
4871
		NSString *expires = [responseHeaders objectForKey:@"Expires"];
4872
		if (expires) {
4873
			return [ASIHTTPRequest dateFromRFC1123String:expires];
4874
		}
4875
	}
4876
	return nil;
4877
}
4878

  
4827 4879
// Based on hints from http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter
4828 4880
+ (NSDate *)dateFromRFC1123String:(NSString *)string
4829 4881
{
......
4947 4999

  
4948 5000
@synthesize username;
4949 5001
@synthesize password;
4950
@synthesize userAgent;
5002
@synthesize userAgentString;
4951 5003
@synthesize domain;
4952 5004
@synthesize proxyUsername;
4953 5005
@synthesize proxyPassword;
b/asi-http-request-with-pithos/Classes/ASIHTTPRequestConfig.h
11 11
// Debug output configuration options
12 12
// ======
13 13

  
14
// If defined will use the specified function for debug logging
15
// Otherwise use NSLog
16
#ifndef ASI_DEBUG_LOG
17
    #define ASI_DEBUG_LOG NSLog
18
#endif
19

  
14 20
// When set to 1 ASIHTTPRequests will print information about what a request is doing
15 21
#ifndef DEBUG_REQUEST_STATUS
16 22
	#define DEBUG_REQUEST_STATUS 0
......
33 39

  
34 40
// When set to 1, ASIHTTPRequests will print information about HTTP authentication (Basic, Digest or NTLM) to the console
35 41
#ifndef DEBUG_HTTP_AUTHENTICATION
36
#define DEBUG_HTTP_AUTHENTICATION 0
42
    #define DEBUG_HTTP_AUTHENTICATION 0
37 43
#endif
b/asi-http-request-with-pithos/Classes/ASIInputStream.m
58 58
		}
59 59
		[request performThrottling];
60 60
	}
61
	[ASIHTTPRequest incrementBandwidthUsedInLastSecond:toRead];
62 61
	[readLock unlock];
63
	return [stream read:buffer maxLength:toRead];
62
	NSInteger rv = [stream read:buffer maxLength:toRead];
63
	if (rv > 0)
64
		[ASIHTTPRequest incrementBandwidthUsedInLastSecond:rv];
65
	return rv;
64 66
}
65 67

  
66 68
/*
b/asi-http-request-with-pithos/Classes/ASIWebPageRequest/ASIWebPageRequest.h
11 11
//  Known issue: You cannot use startSychronous with an ASIWebPageRequest
12 12

  
13 13
#import "ASIHTTPRequest.h"
14
#import <libxml/HTMLparser.h>
15
#import <libxml/xmlsave.h>
16
#import <libxml/xpath.h>
17
#import <libxml/xpathInternals.h>
18 14

  
19 15
@class ASINetworkQueue;
20 16

  
......
52 48
	NSMutableDictionary *resourceList;
53 49

  
54 50
	// Used internally for parsing HTML (with libxml)
55
	xmlDocPtr doc;
51
	struct _xmlDoc *doc;
56 52

  
57 53
	// If the response is an HTML or CSS file, this will be set so the content can be correctly parsed when it has finished fetching external resources
58 54
	ASIWebContentType webContentType;
......
64 60

  
65 61
	// Controls what ASIWebPageRequest does with external resources. See the notes above for more.
66 62
	ASIURLReplacementMode urlReplacementMode;
63

  
64
	// When set to NO, loading will stop when an external resource fails to load. Defaults to YES
65
	BOOL shouldIgnoreExternalResourceErrors;
67 66
}
68 67

  
69 68
// Will return a data URI that contains a base64 version of the content at this url
......
77 76

  
78 77
@property (retain, nonatomic) ASIWebPageRequest *parentRequest;
79 78
@property (assign, nonatomic) ASIURLReplacementMode urlReplacementMode;
79
@property (assign, nonatomic) BOOL shouldIgnoreExternalResourceErrors;
80 80
@end
b/asi-http-request-with-pithos/Classes/ASIWebPageRequest/ASIWebPageRequest.m
10 10
#import "ASIWebPageRequest.h"
11 11
#import "ASINetworkQueue.h"
12 12
#import <CommonCrypto/CommonHMAC.h>
13
#import <libxml/HTMLparser.h>
14
#import <libxml/xmlsave.h>
15
#import <libxml/xpath.h>
16
#import <libxml/xpathInternals.h>
13 17

  
14 18
// An xPath query that controls the external resources ASIWebPageRequest will fetch
15 19
// By default, it will fetch stylesheets, javascript files, images, frames, iframes, and html 5 video / audio
......
45 49
	}
46 50
}
47 51

  
52
- (id)initWithURL:(NSURL *)newURL
53
{
54
	self = [super initWithURL:newURL];
55
	[self setShouldIgnoreExternalResourceErrors:YES];
56
	return self;
57
}
58

  
48 59
- (void)dealloc
49 60
{
50 61
	[externalResourceQueue cancelAllOperations];
......
59 70
// We override it to stop that happening, and instead do that work in the bottom of finishedFetchingExternalResources:
60 71
- (void)markAsFinished
61 72
{
73
	if ([self error]) {
74
		[super markAsFinished];
75
	}
62 76
}
63 77

  
64 78
// This method is normally responsible for telling delegates we are done, but it happens to be the most convenient place to parse the responses
......
120 134
	[[self externalResourceQueue] cancelAllOperations];
121 135
	[self setExternalResourceQueue:[ASINetworkQueue queue]];
122 136
	[[self externalResourceQueue] setDelegate:self];
137
	[[self externalResourceQueue] setShouldCancelAllRequestsOnFailure:[self shouldIgnoreExternalResourceErrors]];
123 138
	[[self externalResourceQueue] setShowAccurateProgress:[self showAccurateProgress]];
124 139
	[[self externalResourceQueue] setQueueDidFinishSelector:@selector(finishedFetchingExternalResources:)];
125 140
	[[self externalResourceQueue] setRequestDidFinishSelector:@selector(externalResourceFetchSucceeded:)];
......
246 261
	[[self externalResourceQueue] cancelAllOperations];
247 262
	[self setExternalResourceQueue:[ASINetworkQueue queue]];
248 263
	[[self externalResourceQueue] setDelegate:self];
264
	[[self externalResourceQueue] setShouldCancelAllRequestsOnFailure:[self shouldIgnoreExternalResourceErrors]];
249 265
	[[self externalResourceQueue] setShowAccurateProgress:[self showAccurateProgress]];
250 266
	[[self externalResourceQueue] setQueueDidFinishSelector:@selector(finishedFetchingExternalResources:)];
251 267
	[[self externalResourceQueue] setRequestDidFinishSelector:@selector(externalResourceFetchSucceeded:)];
......
292 308

  
293 309
- (void)externalResourceFetchFailed:(ASIHTTPRequest *)externalResourceRequest
294 310
{
295
	[self failWithError:[externalResourceRequest error]];
311
	if ([[self externalResourceQueue] shouldCancelAllRequestsOnFailure]) {
312
		[self failWithError:[externalResourceRequest error]];
313
	}
296 314
}
297 315

  
298 316
- (void)finishedFetchingExternalResources:(ASINetworkQueue *)queue
......
700 718
@synthesize resourceList;
701 719
@synthesize parentRequest;
702 720
@synthesize urlReplacementMode;
721
@synthesize shouldIgnoreExternalResourceErrors;
703 722
@end
b/asi-http-request-with-pithos/Classes/CloudFiles/ASICloudFilesCDNRequest.h
24 24
// Response:
25 25
// X-CDN-Enabled: True
26 26
// X-CDN-URI: http://cdn.cloudfiles.mosso.com/c1234
27
// X-CDN-SSL-URI: https://cdn.ssl.cloudfiles.mosso.com/c1234
27 28
// X-CDN-TTL: 86400
28 29
+ (id)containerInfoRequest:(NSString *)containerName;
29 30
- (BOOL)cdnEnabled;
30 31
- (NSString *)cdnURI;
32
- (NSString *)cdnSSLURI;
31 33
- (NSUInteger)cdnTTL;
32 34

  
33 35

  
b/asi-http-request-with-pithos/Classes/CloudFiles/ASICloudFilesCDNRequest.m
38 38
}
39 39

  
40 40
- (BOOL)cdnEnabled {
41
	return [[[self responseHeaders] objectForKey:@"X-Cdn-Enabled"] boolValue];
41
    NSNumber *enabled = [[self responseHeaders] objectForKey:@"X-CDN-Enabled"];
42
    if (!enabled) {
43
        enabled = [[self responseHeaders] objectForKey:@"X-Cdn-Enabled"];
44
    }
45
	return [enabled boolValue];
42 46
}
43 47

  
44 48
- (NSString *)cdnURI {
45
	return [[self responseHeaders] objectForKey:@"X-Cdn-Uri"];
49
	NSString *uri = [[self responseHeaders] objectForKey:@"X-CDN-URI"];
50
    if (!uri) {
51
        uri = [[self responseHeaders] objectForKey:@"X-Cdn-Uri"];
52
    }
53
    return uri;
54
}
55

  
56
- (NSString *)cdnSSLURI {
57
    NSString *uri = [[self responseHeaders] objectForKey:@"X-CDN-SSL-URI"];
58
    if (!uri) {
59
        uri = [[self responseHeaders] objectForKey:@"X-Cdn-Ssl-Uri"];
60
    }
61
	return uri;
46 62
}
47 63

  
48 64
- (NSUInteger)cdnTTL {
49
	return [[[self responseHeaders] objectForKey:@"X-Ttl"] intValue];
65
    NSNumber *ttl = [[self responseHeaders] objectForKey:@"X-TTL"];
66
    if (!ttl) {
67
        ttl = [[self responseHeaders] objectForKey:@"X-Ttl"];
68
    }
69
    return [ttl intValue];
50 70
}
51 71

  
52 72
#pragma mark -
......
130 150
	if (ttl > 0) {
131 151
		[request addRequestHeader:@"X-Ttl" value:[NSString stringWithFormat:@"%i", ttl]];
132 152
	}
133
	[request addRequestHeader:@"X-Cdn-Enabled" value:cdnEnabled ? @"True" : @"False"];
153
	[request addRequestHeader:@"X-CDN-Enabled" value:cdnEnabled ? @"True" : @"False"];
134 154
	return request;
135 155
}
136 156

  
b/asi-http-request-with-pithos/Classes/CloudFiles/ASICloudFilesContainer.m
22 22

  
23 23
-(void) dealloc {
24 24
	[name release];
25
	[cdnURL release];
26
	[referrerACL release];
27
	[useragentACL release];
25 28
	[super dealloc];
26 29
}
27 30

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff