Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Full Support for Google Reader Sync!

  • Loading branch information...
commit d2d4ed04a076e5781c9eb59c2002d6ff22c7561f 1 parent 5831876
authored January 09, 2012

Showing 60 changed files with 9,915 additions and 887 deletions. Show diff stats Hide diff stats

  1. 0  ASICacheDelegate.h
  2. 0  ASIDataCompressor.h
  3. 10  ASIDataCompressor.m
  4. 0  ASIDataDecompressor.h
  5. 10  ASIDataDecompressor.m
  6. 4  ASIDownloadCache.h
  7. 61  ASIDownloadCache.m
  8. 0  ASIFormDataRequest.h
  9. 5  ASIFormDataRequest.m
  10. 5  ASIHTTPRequest.h
  11. 242  ASIHTTPRequest.m
  12. 8  ASIHTTPRequestConfig.h
  13. 0  ASIHTTPRequestDelegate.h
  14. 0  ASIInputStream.h
  15. 6  ASIInputStream.m
  16. 0  ASINetworkQueue.h
  17. 0  ASINetworkQueue.m
  18. 0  ASIProgressDelegate.h
  19. 6  AppController.h
  20. 143  AppController.m
  21. 43  ArticleController.m
  22. 2  ArticleListView.h
  23. 4  ArticleListView.m
  24. 3  Database.h
  25. 35  Database.m
  26. 2  DownloadManager.h
  27. 2  DownloadWindow.h
  28. 2  Folder.h
  29. 8  Folder.m
  30. 2  FoldersTree.m
  31. 53  GRSOperation.m
  32. 4  GRSRefreshOperation.h
  33. 2  GRSRefreshOperation.m
  34. 187  GTMHTTPFetchHistory.h
  35. 591  GTMHTTPFetchHistory.m
  36. 675  GTMHTTPFetcher.h
  37. 1,604  GTMHTTPFetcher.m
  38. 85  GTMHTTPFetcherLogging.h
  39. 1,001  GTMHTTPFetcherLogging.m
  40. 322  GTMOAuth2Authentication.h
  41. 1,136  GTMOAuth2Authentication.m
  42. 173  GTMOAuth2SignIn.h
  43. 806  GTMOAuth2SignIn.m
  44. 657  GTMOAuth2Window.xib
  45. 332  GTMOAuth2WindowController.h
  46. 727  GTMOAuth2WindowController.m
  47. 24  GoogleReader.h
  48. 835  GoogleReader.m
  49. 2  InfoWindow.h
  50. 52  RefreshManager.m
  51. 7  SNDisclosableView.m
  52. 4  SyncMerge.h
  53. 20  SyncMerge.m
  54. 7  SyncPreferences.m
  55. 538  SyncPreferences.xib
  56. 39  VTPG_Common.h
  57. 98  VTPG_Common.m
  58. 196  Vienna.xcodeproj/project.pbxproj
  59. 22  ViennaApp.m
  60. BIN  googleFeed.tiff
0  ASICacheDelegate.h 100755 → 100644
File mode changed
0  ASIDataCompressor.h 100755 → 100644
File mode changed
10  ASIDataCompressor.m 100755 → 100644
@@ -78,7 +78,7 @@ - (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSErro
78 78
 	int status;
79 79
 	
80 80
 	zStream.next_in = bytes;
81  
-	zStream.avail_in = (NSUInteger )length;
  81
+	zStream.avail_in = (unsigned int)length;
82 82
 	zStream.avail_out = 0;
83 83
 
84 84
 	NSInteger bytesProcessedAlready = zStream.total_out;
@@ -88,8 +88,8 @@ - (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSErro
88 88
 			[outputData increaseLengthBy:halfLength];
89 89
 		}
90 90
 		
91  
-		zStream.next_out = [outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
92  
-		zStream.avail_out = (NSUInteger )([outputData length] - (zStream.total_out-bytesProcessedAlready));
  91
+		zStream.next_out = (Bytef*)[outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
  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
 		
95 95
 		if (status == Z_STREAM_END) {
@@ -184,12 +184,12 @@ + (BOOL)compressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinati
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;
0  ASIDataDecompressor.h 100755 → 100644
File mode changed
10  ASIDataDecompressor.m 100755 → 100644
@@ -75,7 +75,7 @@ - (NSData *)uncompressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSEr
75 75
 	int status;
76 76
 	
77 77
 	zStream.next_in = bytes;
78  
-	zStream.avail_in = (NSUInteger )length;
  78
+	zStream.avail_in = (unsigned int)length;
79 79
 	zStream.avail_out = 0;
80 80
 	
81 81
 	NSInteger bytesProcessedAlready = zStream.total_out;
@@ -85,8 +85,8 @@ - (NSData *)uncompressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSEr
85 85
 			[outputData increaseLengthBy:halfLength];
86 86
 		}
87 87
 		
88  
-		zStream.next_out = [outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
89  
-		zStream.avail_out = (NSUInteger )([outputData length] - (zStream.total_out-bytesProcessedAlready));
  88
+		zStream.next_out = (Bytef*)[outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
  89
+		zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready));
90 90
 		
91 91
 		status = inflate(&zStream, Z_NO_FLUSH);
92 92
 		
@@ -181,12 +181,12 @@ + (BOOL)uncompressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destina
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;
4  ASIDownloadCache.h 100755 → 100644
@@ -35,6 +35,10 @@
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;
61  ASIDownloadCache.m 100755 → 100644
@@ -14,6 +14,7 @@
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,6 +23,15 @@ - (NSString *)pathToFile:(NSString *)file;
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,31 +115,7 @@ - (void)updateExpiryForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)
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,9 +169,14 @@ - (void)storeResponseForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval
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,12 +203,21 @@ - (NSString *)pathToCachedResponseDataForURL:(NSURL *)url
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,7 +262,10 @@ - (NSString *)pathToStoreCachedResponseDataForRequest:(ASIHTTPRequest *)request
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]];
0  ASIFormDataRequest.h 100755 → 100644
File mode changed
5  ASIFormDataRequest.m 100755 → 100644
@@ -30,7 +30,7 @@ @implementation ASIFormDataRequest
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,6 +49,7 @@ - (id)initWithURL:(NSURL *)newURL
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,7 +208,7 @@ - (void)buildPostBody
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
 }
5  ASIHTTPRequest.h 100755 → 100644
@@ -873,6 +873,11 @@ typedef void (^ASIDataBlock)(NSData *data);
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
 
242  ASIHTTPRequest.m 100755 → 100644
@@ -24,7 +24,7 @@
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
 
@@ -69,7 +69,7 @@ static void ReadStreamClientCallBack(CFReadStreamRef readStream, CFStreamEventTy
69 69
 // These are used for queuing persistent connections on the same connection
70 70
 
71 71
 // Incremented every time we specify we want a new connection
72  
-static NSUInteger  nextConnectionNumberToCreate = 0;
  72
+static unsigned int nextConnectionNumberToCreate = 0;
73 73
 
74 74
 // An array of connectionInfo dictionaries.
75 75
 // When attempting a persistent connection, we look here to try to find an existing connection to the same server that is currently not in use
@@ -80,7 +80,7 @@ static void ReadStreamClientCallBack(CFReadStreamRef readStream, CFStreamEventTy
80 80
 
81 81
 // Each request gets a new id, we store this rather than a ref to the request itself in the connectionInfo dictionary.
82 82
 // We do this so we don't have to keep the request around while we wait for the connection to expire
83  
-static NSUInteger  nextRequestID = 0;
  83
+static unsigned int nextRequestID = 0;
84 84
 
85 85
 // Records how much bandwidth all requests combined have used in the last second
86 86
 static unsigned long bandwidthUsedInLastSecond = 0; 
@@ -105,7 +105,7 @@ static void ReadStreamClientCallBack(CFReadStreamRef readStream, CFStreamEventTy
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
@@ -124,7 +124,7 @@ static void ReadStreamClientCallBack(CFReadStreamRef readStream, CFStreamEventTy
124 124
 static id <ASICacheDelegate> defaultCache = nil;
125 125
 
126 126
 // Used for tracking when requests are using the network
127  
-static NSUInteger  runningRequestCount = 0;
  127
+static unsigned int runningRequestCount = 0;
128 128
 
129 129
 // You can use [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO] if you want to manage it yourself
130 130
 // Alternatively, override showNetworkActivityIndicator / hideNetworkActivityIndicator
@@ -696,7 +696,7 @@ - (void)setQueue:(id)newQueue
696 696
 - (void)cancelOnRequestThread
697 697
 {
698 698
 	#if DEBUG_REQUEST_STATUS
699  
-	NSLog(@"[STATUS] Request cancelled: %@",self);
  699
+	ASI_DEBUG_LOG(@"[STATUS] Request cancelled: %@",self);
700 700
 	#endif
701 701
     
702 702
 	[[self cancelledLock] lock];
@@ -786,7 +786,7 @@ - (NSData *)responseData
786 786
 - (void)startSynchronous
787 787
 {
788 788
 #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
789  
-	NSLog(@"[STATUS] Starting synchronous request %@",self);
  789
+	ASI_DEBUG_LOG(@"[STATUS] Starting synchronous request %@",self);
790 790
 #endif
791 791
 	[self setSynchronous:YES];
792 792
 	[self setRunLoopMode:ASIHTTPRequestRunLoopMode];
@@ -811,7 +811,7 @@ - (void)start
811 811
 - (void)startAsynchronous
812 812
 {
813 813
 #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
814  
-	NSLog(@"[STATUS] Starting asynchronous request %@",self);
  814
+	ASI_DEBUG_LOG(@"[STATUS] Starting asynchronous request %@",self);
815 815
 #endif
816 816
 	[sharedQueue addOperation:self];
817 817
 }
@@ -962,7 +962,7 @@ - (void)applyAuthorizationHeader
962 962
 	// Do we want to send credentials before we are asked for them?
963 963
 	if (![self shouldPresentCredentialsBeforeChallenge]) {
964 964
 		#if DEBUG_HTTP_AUTHENTICATION
965  
-		NSLog(@"[AUTH] Request %@ will not send credentials to the server until it asks for them",self);
  965
+		ASI_DEBUG_LOG(@"[AUTH] Request %@ will not send credentials to the server until it asks for them",self);
966 966
 		#endif
967 967
 		return;
968 968
 	}
@@ -977,7 +977,7 @@ - (void)applyAuthorizationHeader
977 977
 			[self addBasicAuthenticationHeaderWithUsername:[self username] andPassword:[self password]];
978 978
 
979 979
 			#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);	
  980
+			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 981
 			#endif
982 982
 
983 983
 		} else {
@@ -996,12 +996,12 @@ - (void)applyAuthorizationHeader
996 996
 						if (CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
997 997
 							[self setAuthenticationScheme:[credentials objectForKey:@"AuthenticationScheme"]];
998 998
 							#if DEBUG_HTTP_AUTHENTICATION
999  
-							NSLog(@"[AUTH] Request %@ found cached credentials (%@), will reuse without waiting for an authentication challenge",self,[credentials objectForKey:@"AuthenticationScheme"]);
  999
+							ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached credentials (%@), will reuse without waiting for an authentication challenge",self,[credentials objectForKey:@"AuthenticationScheme"]);
1000 1000
 							#endif
1001 1001
 						} else {
1002 1002
 							[[self class] removeAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
1003 1003
 							#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);
  1004
+							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 1005
 							#endif
1006 1006
 						}
1007 1007
 
@@ -1011,7 +1011,7 @@ - (void)applyAuthorizationHeader
1011 1011
 						NSDictionary *usernameAndPassword = [credentials objectForKey:@"Credentials"];
1012 1012
 						[self addBasicAuthenticationHeaderWithUsername:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername] andPassword:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword]];
1013 1013
 						#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);
  1014
+						ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached BASIC credentials from a previous request. Will send credentials without waiting for an authentication challenge",self);
1015 1015
 						#endif
1016 1016
 					}
1017 1017
 				}
@@ -1169,7 +1169,7 @@ - (void)startRequest
1169 1169
 		} else {
1170 1170
 			[self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self postBodyFilePath] request:self]];
1171 1171
 		}
1172  
-		[self setReadStream:[(NSInputStream *)CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream]) autorelease]];
  1172
+		[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];    
1173 1173
     } else {
1174 1174
 		
1175 1175
 		// 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,10 +1179,10 @@ - (void)startRequest
1179 1179
 			} else if ([self postBody]) {
1180 1180
 				[self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self postBody] request:self]];
1181 1181
 			}
1182  
-			[self setReadStream:[(NSInputStream *)CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream]) autorelease]];
  1182
+			[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];
1183 1183
 		
1184 1184
 		} else {
1185  
-			[self setReadStream:[(NSInputStream *)CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request) autorelease]];
  1185
+			[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request)) autorelease]];
1186 1186
 		}
1187 1187
 	}
1188 1188
 
@@ -1198,18 +1198,28 @@ - (void)startRequest
1198 1198
     // Handle SSL certificate settings
1199 1199
     //
1200 1200
 
1201  
-    if([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {
1202  
-
1203  
-        NSMutableDictionary *sslProperties = [NSMutableDictionary dictionaryWithCapacity:1];
1204  
-
  1201
+    if([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {       
  1202
+       
1205 1203
         // Tell CFNetwork not to validate SSL certificates
1206 1204
         if (![self validatesSecureCertificate]) {
1207  
-            [sslProperties setObject:(NSString *)kCFBooleanFalse forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];
1208  
-        }
1209  
-
  1205
+            // see: http://iphonedevelopment.blogspot.com/2010/05/nsstream-tcp-and-ssl.html
  1206
+            
  1207
+            NSDictionary *sslProperties = [[NSDictionary alloc] initWithObjectsAndKeys:
  1208
+                                      [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
  1209
+                                      [NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
  1210
+                                      [NSNumber numberWithBool:NO],  kCFStreamSSLValidatesCertificateChain,
  1211
+                                      kCFNull,kCFStreamSSLPeerName,
  1212
+                                      nil];
  1213
+            
  1214
+            CFReadStreamSetProperty((CFReadStreamRef)[self readStream], 
  1215
+                                    kCFStreamPropertySSLSettings, 
  1216
+                                    (CFTypeRef)sslProperties);
  1217
+        } 
  1218
+        
1210 1219
         // Tell CFNetwork to use a client certificate
1211 1220
         if (clientCertificateIdentity) {
1212  
-
  1221
+            NSMutableDictionary *sslProperties = [NSMutableDictionary dictionaryWithCapacity:1];
  1222
+            
1213 1223
 			NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[clientCertificates count]+1];
1214 1224
 
1215 1225
 			// The first object in the array is our SecIdentityRef
@@ -1219,10 +1229,12 @@ - (void)startRequest
1219 1229
 			for (id cert in clientCertificates) {
1220 1230
 				[certificates addObject:cert];
1221 1231
 			}
  1232
+            
1222 1233
             [sslProperties setObject:certificates forKey:(NSString *)kCFStreamSSLCertificates];
  1234
+            
  1235
+            CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, sslProperties);
1223 1236
         }
1224  
-
1225  
-        CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, sslProperties);
  1237
+        
1226 1238
     }
1227 1239
 
1228 1240
 	//
@@ -1288,7 +1300,7 @@ - (void)startRequest
1288 1300
 			// Check if we should have expired this connection
1289 1301
 			} else if ([[[self connectionInfo] objectForKey:@"expires"] timeIntervalSinceNow] < 0) {
1290 1302
 				#if DEBUG_PERSISTENT_CONNECTIONS
1291  
-				NSLog(@"[CONNECTION] Not re-using connection #%i because it has expired",[[[self connectionInfo] objectForKey:@"id"] intValue]);
  1303
+				ASI_DEBUG_LOG(@"[CONNECTION] Not re-using connection #%i because it has expired",[[[self connectionInfo] objectForKey:@"id"] intValue]);
1292 1304
 				#endif
1293 1305
 				[persistentConnectionsPool removeObject:[self connectionInfo]];
1294 1306
 				[self setConnectionInfo:nil];
@@ -1296,7 +1308,7 @@ - (void)startRequest
1296 1308
 			} else if ([[self connectionInfo] objectForKey:@"request"] != nil) {
1297 1309
                 //Some other request reused this connection already - we'll have to create a new one
1298 1310
 				#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]);
  1311
+                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 1312
 				#endif
1301 1313
                 [self setConnectionInfo:nil];
1302 1314
             }
@@ -1340,7 +1352,7 @@ - (void)startRequest
1340 1352
 		CFReadStreamSetProperty((CFReadStreamRef)[self readStream],  kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue);
1341 1353
 		
1342 1354
 		#if DEBUG_PERSISTENT_CONNECTIONS
1343  
-		NSLog(@"[CONNECTION] Request #%@ will use connection #%i",[self requestID],[[[self connectionInfo] objectForKey:@"id"] intValue]);
  1355
+		ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ will use connection #%i",[self requestID],[[[self connectionInfo] objectForKey:@"id"] intValue]);
1344 1356
 		#endif
1345 1357
 		
1346 1358
 		
@@ -1351,7 +1363,7 @@ - (void)startRequest
1351 1363
 	
1352 1364
 	} else {
1353 1365
 		#if DEBUG_PERSISTENT_CONNECTIONS
1354  
-		NSLog(@"[CONNECTION] Request %@ will not use a persistent connection",self);
  1366
+		ASI_DEBUG_LOG(@"[CONNECTION] Request %@ will not use a persistent connection",self);
1355 1367
 		#endif
1356 1368
 	}
1357 1369
 	
@@ -1519,7 +1531,7 @@ - (void)checkRequestStatus
1519 1531
 			[self setLastBytesSent:totalBytesSent];	
1520 1532
 			
1521 1533
 			// Find out how much data we've uploaded so far
1522  
-			[self setTotalBytesSent:[NSMakeCollectable([(NSNumber *)CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount) autorelease]) unsignedLongLongValue]];
  1534
+			[self setTotalBytesSent:[[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) autorelease] unsignedLongLongValue]];
1523 1535
 			if (totalBytesSent > lastBytesSent) {
1524 1536
 				
1525 1537
 				// We've uploaded more data,  reset the timeout
@@ -1528,7 +1540,7 @@ - (void)checkRequestStatus
1528 1540
 						
1529 1541
 				#if DEBUG_REQUEST_STATUS
1530 1542
 				if ([self totalBytesSent] == [self postLength]) {
1531  
-					NSLog(@"[STATUS] Request %@ finished uploading data",self);
  1543
+					ASI_DEBUG_LOG(@"[STATUS] Request %@ finished uploading data",self);
1532 1544
 				}
1533 1545
 				#endif
1534 1546
 			}
@@ -1985,7 +1997,7 @@ - (void)requestWillRedirectToURL:(NSURL *)newURL
1985 1997
 - (void)requestFinished
1986 1998
 {
1987 1999
 #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
1988  
-	NSLog(@"[STATUS] Request finished: %@",self);
  2000
+	ASI_DEBUG_LOG(@"[STATUS] Request finished: %@",self);
1989 2001
 #endif
1990 2002
 	if ([self error] || [self mainRequest]) {
1991 2003
 		return;
@@ -2052,7 +2064,7 @@ - (void)passOnReceivedData:(NSData *)data
2052 2064
 - (void)failWithError:(NSError *)theError
2053 2065
 {
2054 2066
 #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
2055  
-	NSLog(@"[STATUS] Request %@: %@",self,(theError == ASIRequestCancelledError ? @"Cancelled" : @"Failed"));
  2067
+	ASI_DEBUG_LOG(@"[STATUS] Request %@: %@",self,(theError == ASIRequestCancelledError ? @"Cancelled" : @"Failed"));
2056 2068
 #endif
2057 2069
 	[self setComplete:YES];
2058 2070
 	
@@ -2060,7 +2072,7 @@ - (void)failWithError:(NSError *)theError
2060 2072
 	if (theError && [theError code] != ASIAuthenticationErrorType && [theError code] != ASITooMuchRedirectionErrorType) {
2061 2073
 		[connectionsLock lock];
2062 2074
 		#if DEBUG_PERSISTENT_CONNECTIONS
2063  
-		NSLog(@"[CONNECTION] Request #%@ failed and will invalidate connection #%@",[self requestID],[[self connectionInfo] objectForKey:@"id"]);
  2075
+		ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ failed and will invalidate connection #%@",[self requestID],[[self connectionInfo] objectForKey:@"id"]);
2064 2076
 		#endif
2065 2077
 		[[self connectionInfo] removeObjectForKey:@"request"];
2066 2078
 		[persistentConnectionsPool removeObject:[self connectionInfo]];
@@ -2128,13 +2140,13 @@ - (void)readResponseHeaders
2128 2140
 
2129 2141
 	#if DEBUG_REQUEST_STATUS
2130 2142
 	if ([self totalBytesSent] == [self postLength]) {
2131  
-		NSLog(@"[STATUS] Request %@ received response headers",self);
  2143
+		ASI_DEBUG_LOG(@"[STATUS] Request %@ received response headers",self);
2132 2144
 	}
2133 2145
 	#endif		
2134 2146
 
2135  
-	[self setResponseHeaders:[(NSDictionary *)CFHTTPMessageCopyAllHeaderFields(message) autorelease]];
  2147
+	[self setResponseHeaders:[NSMakeCollectable(CFHTTPMessageCopyAllHeaderFields(message)) autorelease]];
2136 2148
 	[self setResponseStatusCode:(int)CFHTTPMessageGetResponseStatusCode(message)];
2137  
-	[self setResponseStatusMessage:[(NSString *)CFHTTPMessageCopyResponseStatusLine(message) autorelease]];
  2149
+	[self setResponseStatusMessage:[NSMakeCollectable(CFHTTPMessageCopyResponseStatusLine(message)) autorelease]];
2138 2150
 
2139 2151
 	if ([self downloadCache] && ([[self downloadCache] canUseCachedDataForRequest:self])) {
2140 2152
 
@@ -2156,7 +2168,7 @@ - (void)readResponseHeaders
2156 2168
 	} else {
2157 2169
 		#if DEBUG_HTTP_AUTHENTICATION
2158 2170
 		if ([self authenticationScheme]) {
2159  
-			NSLog(@"[AUTH] Request %@ has passed %@ authentication",self,[self authenticationScheme]);
  2171
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ has passed %@ authentication",self,[self authenticationScheme]);
2160 2172
 		}
2161 2173
 		#endif
2162 2174
 	}
@@ -2168,7 +2180,7 @@ - (void)readResponseHeaders
2168 2180
 		if (!requestAuthentication && [[self authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic] && [self username] && [self password] && [self useSessionPersistence]) {
2169 2181
 
2170 2182
 			#if DEBUG_HTTP_AUTHENTICATION
2171  
-			NSLog(@"[AUTH] Request %@ passed BASIC authentication, and will save credentials in the session store for future use",self);
  2183
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ passed BASIC authentication, and will save credentials in the session store for future use",self);
2172 2184
 			#endif
2173 2185
 			
2174 2186
 			NSMutableDictionary *newCredentials = [NSMutableDictionary dictionaryWithCapacity:2];
@@ -2238,7 +2250,7 @@ - (void)readResponseHeaders
2238 2250
 		
2239 2251
 		NSString *connectionHeader = [[[self responseHeaders] objectForKey:@"Connection"] lowercaseString];
2240 2252
 
2241  
-		NSString *httpVersion = NSMakeCollectable([(NSString *)CFHTTPMessageCopyVersion(message) autorelease]);
  2253
+		NSString *httpVersion = [NSMakeCollectable(CFHTTPMessageCopyVersion(message)) autorelease];
2242 2254
 		
2243 2255
 		// Don't re-use the connection if the server is HTTP 1.0 and didn't send Connection: Keep-Alive
2244 2256
 		if (![httpVersion isEqualToString:(NSString *)kCFHTTPVersion1_0] || [connectionHeader isEqualToString:@"keep-alive"]) {
@@ -2262,7 +2274,7 @@ - (void)readResponseHeaders
2262 2274
 						[self setConnectionCanBeReused:YES];
2263 2275
 						[self setPersistentConnectionTimeoutSeconds:timeout];
2264 2276
 						#if DEBUG_PERSISTENT_CONNECTIONS
2265  
-							NSLog(@"[CONNECTION] Got a keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
  2277
+							ASI_DEBUG_LOG(@"[CONNECTION] Got a keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
2266 2278
 						#endif					
2267 2279
 					}
2268 2280
 				
@@ -2270,7 +2282,7 @@ - (void)readResponseHeaders
2270 2282
 				} else {
2271 2283
 					[self setConnectionCanBeReused:YES];
2272 2284
 					#if DEBUG_PERSISTENT_CONNECTIONS
2273  
-						NSLog(@"[CONNECTION] Got no keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
  2285
+						ASI_DEBUG_LOG(@"[CONNECTION] Got no keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
2274 2286
 					#endif
2275 2287
 				}
2276 2288
 			}
@@ -2334,7 +2346,7 @@ - (BOOL)willRedirect
2334 2346
 	[self setRequestCookies:[NSMutableArray array]];
2335 2347
 
2336 2348
 	#if DEBUG_REQUEST_STATUS
2337  
-	NSLog(@"[STATUS] Request will redirect (code: %i): %@",responseCode,self);
  2349
+	ASI_DEBUG_LOG(@"[STATUS] Request will redirect (code: %i): %@",responseCode,self);
2338 2350
 	#endif
2339 2351
 
2340 2352
 	return YES;
@@ -2523,7 +2535,7 @@ - (NSMutableDictionary *)findCredentials
2523 2535
 	if (user && pass) {
2524 2536
 
2525 2537
 		#if DEBUG_HTTP_AUTHENTICATION
2526  
-		NSLog(@"[AUTH] Request %@ will use credentials set on its url",self);
  2538
+		ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials set on its url",self);
2527 2539
 		#endif
2528 2540
 
2529 2541
 	} else {
@@ -2534,7 +2546,7 @@ - (NSMutableDictionary *)findCredentials
2534 2546
 			pass = [[self mainRequest] password];
2535 2547
 
2536 2548
 			#if DEBUG_HTTP_AUTHENTICATION
2537  
-			NSLog(@"[AUTH] Request %@ will use credentials from its parent request",self);
  2549
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from its parent request",self);
2538 2550
 			#endif
2539 2551
 
2540 2552
 		// Let's try to use the ones set in this object
@@ -2543,7 +2555,7 @@ - (NSMutableDictionary *)findCredentials
2543 2555
 			pass = [self password];
2544 2556
 
2545 2557
 			#if DEBUG_HTTP_AUTHENTICATION
2546  
-			NSLog(@"[AUTH] Request %@ will use username and password properties as credentials",self);
  2558
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ will use username and password properties as credentials",self);
2547 2559
 			#endif
2548 2560
 		}		
2549 2561
 	}
@@ -2556,7 +2568,7 @@ - (NSMutableDictionary *)findCredentials
2556 2568
 			pass = [authenticationCredentials password];
2557 2569
 			#if DEBUG_HTTP_AUTHENTICATION
2558 2570
 			if (user && pass) {
2559  
-				NSLog(@"[AUTH] Request %@ will use credentials from the keychain",self);
  2571
+				ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from the keychain",self);
2560 2572
 			}
2561 2573
 			#endif
2562 2574
 		}
@@ -2592,7 +2604,7 @@ - (NSMutableDictionary *)findCredentials
2592 2604
 - (void)retryUsingSuppliedCredentials
2593 2605
 {
2594 2606
 	#if DEBUG_HTTP_AUTHENTICATION
2595  
-		NSLog(@"[AUTH] Request %@ received credentials from its delegate or an ASIAuthenticationDialog, will retry",self);
  2607
+		ASI_DEBUG_LOG(@"[AUTH] Request %@ received credentials from its delegate or an ASIAuthenticationDialog, will retry",self);
2596 2608
 	#endif
2597 2609
 	//If the url was changed by the delegate, our CFHTTPMessageRef will be NULL and we'll go back to the start
2598 2610
 	if (!request) {
@@ -2606,7 +2618,7 @@ - (void)retryUsingSuppliedCredentials
2606 2618
 - (void)cancelAuthentication
2607 2619
 {
2608 2620
 	#if DEBUG_HTTP_AUTHENTICATION
2609  
-		NSLog(@"[AUTH] Request %@ had authentication cancelled by its delegate or an ASIAuthenticationDialog",self);
  2621
+		ASI_DEBUG_LOG(@"[AUTH] Request %@ had authentication cancelled by its delegate or an ASIAuthenticationDialog",self);
2610 2622
 	#endif
2611 2623
 	[self performSelector:@selector(failAuthentication) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
2612 2624
 }
@@ -2749,7 +2761,7 @@ - (void)attemptToApplyProxyCredentialsAndResume
2749 2761
 		CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
2750 2762
 		proxyAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
2751 2763
 		CFRelease(responseHeader);
2752  
-		[self setProxyAuthenticationScheme:[(NSString *)CFHTTPAuthenticationCopyMethod(proxyAuthentication) autorelease]];
  2764
+		[self setProxyAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(proxyAuthentication)) autorelease]];
2753 2765
 	}
2754 2766
 	
2755 2767
 	// If we haven't got a CFHTTPAuthenticationRef by now, something is badly wrong, so we'll have to give up
@@ -2762,7 +2774,7 @@ - (void)attemptToApplyProxyCredentialsAndResume
2762 2774
 	// Get the authentication realm
2763 2775
 	[self setProxyAuthenticationRealm:nil];
2764 2776
 	if (!CFHTTPAuthenticationRequiresAccountDomain(proxyAuthentication)) {
2765  
-		[self setProxyAuthenticationRealm:[(NSString *)CFHTTPAuthenticationCopyRealm(proxyAuthentication) autorelease]];
  2777
+		[self setProxyAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(proxyAuthentication)) autorelease]];
2766 2778
 	}
2767 2779
 	
2768 2780
 	// See if authentication is valid
@@ -2926,12 +2938,12 @@ - (void)attemptToApplyCredentialsAndResume
2926 2938
 		CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
2927 2939
 		requestAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
2928 2940
 		CFRelease(responseHeader);
2929  
-		[self setAuthenticationScheme:[(NSString *)CFHTTPAuthenticationCopyMethod(requestAuthentication) autorelease]];
  2941
+		[self setAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(requestAuthentication)) autorelease]];
2930 2942
 	}
2931 2943
 	
2932 2944
 	if (!requestAuthentication) {
2933 2945
 		#if DEBUG_HTTP_AUTHENTICATION
2934  
-		NSLog(@"[AUTH] Request %@ failed to read authentication information from response headers",self);
  2946
+		ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to read authentication information from response headers",self);
2935 2947
 		#endif
2936 2948
 
2937 2949
 		[self cancelLoad];
@@ -2942,7 +2954,7 @@ - (void)attemptToApplyCredentialsAndResume
2942 2954
 	// Get the authentication realm
2943 2955
 	[self setAuthenticationRealm:nil];
2944 2956
 	if (!CFHTTPAuthenticationRequiresAccountDomain(requestAuthentication)) {
2945  
-		[self setAuthenticationRealm:[(NSString *)CFHTTPAuthenticationCopyRealm(requestAuthentication) autorelease]];
  2957
+		[self setAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(requestAuthentication)) autorelease]];
2946 2958
 	}
2947 2959
 	
2948 2960
 	#if DEBUG_HTTP_AUTHENTICATION
@@ -2953,9 +2965,9 @@ - (void)attemptToApplyCredentialsAndResume
2953 2965
 			realm = @"";
2954 2966
 		}
2955 2967
 		if ([self authenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM || [self authenticationRetryCount] == 0) {
2956  
-			NSLog(@"[AUTH] Request %@ received 401 challenge and must authenticate using %@%@",self,[self authenticationScheme],realm);
  2968
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ received 401 challenge and must authenticate using %@%@",self,[self authenticationScheme],realm);
2957 2969
 		} else {
2958  
-			NSLog(@"[AUTH] Request %@ NTLM handshake step %i",self,[self authenticationRetryCount]+1);
  2970
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ NTLM handshake step %i",self,[self authenticationRetryCount]+1);
2959 2971
 		}
2960 2972
 	#endif
2961 2973
 
@@ -2970,7 +2982,7 @@ - (void)attemptToApplyCredentialsAndResume
2970 2982
 		if (err.domain == kCFStreamErrorDomainHTTP && (err.error == kCFStreamErrorHTTPAuthenticationBadUserName || err.error == kCFStreamErrorHTTPAuthenticationBadPassword)) {
2971 2983
 
2972 2984
 			#if DEBUG_HTTP_AUTHENTICATION
2973  
-			NSLog(@"[AUTH] Request %@ had bad credentials, will remove them from the session store if they are cached",self);
  2985
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ had bad credentials, will remove them from the session store if they are cached",self);
2974 2986
 			#endif
2975 2987
 
2976 2988
 			// Prevent more than one request from asking for credentials at once
@@ -2984,7 +2996,7 @@ - (void)attemptToApplyCredentialsAndResume
2984 2996
 			if ([self error] || [self isCancelled]) {
2985 2997
 
2986 2998
 				#if DEBUG_HTTP_AUTHENTICATION
2987  
-				NSLog(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
  2999
+				ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
2988 3000
 				#endif
2989 3001
 
2990 3002
 				[delegateAuthenticationLock unlock];
@@ -2997,7 +3009,7 @@ - (void)attemptToApplyCredentialsAndResume
2997 3009
 				if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
2998 3010
 
2999 3011
 					#if DEBUG_HTTP_AUTHENTICATION
3000  
-					NSLog(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
  3012
+					ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
3001 3013
 					#endif
3002 3014
 
3003 3015
 					[delegateAuthenticationLock unlock];
@@ -3011,7 +3023,7 @@ - (void)attemptToApplyCredentialsAndResume
3011 3023
 			if ([self willAskDelegateForCredentials]) {
3012 3024
 
3013 3025
 				#if DEBUG_HTTP_AUTHENTICATION
3014  
-				NSLog(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
  3026
+				ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
3015 3027
 				#endif
3016 3028
 
3017 3029
 				[delegateAuthenticationLock unlock];
@@ -3020,7 +3032,7 @@ - (void)attemptToApplyCredentialsAndResume
3020 3032
 			if ([self showAuthenticationDialog]) {
3021 3033
 
3022 3034
 				#if DEBUG_HTTP_AUTHENTICATION
3023  
-				NSLog(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
  3035
+				ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
3024 3036
 				#endif
3025 3037
 
3026 3038
 				[delegateAuthenticationLock unlock];
@@ -3030,7 +3042,7 @@ - (void)attemptToApplyCredentialsAndResume
3030 3042
 		}
3031 3043
 
3032 3044
 		#if DEBUG_HTTP_AUTHENTICATION
3033  
-		NSLog(@"[AUTH] Request %@ has no credentials to present and must give up",self);
  3045
+		ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
3034 3046
 		#endif
3035 3047
 
3036 3048
 		[self cancelLoad];
@@ -3048,7 +3060,7 @@ - (void)attemptToApplyCredentialsAndResume
3048 3060
 			// We've failed NTLM authentication twice, we should assume our credentials are wrong
3049 3061
 		} else if ([self authenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM && [self authenticationRetryCount ] == 2) {
3050 3062
 			#if DEBUG_HTTP_AUTHENTICATION
3051  
-			NSLog(@"[AUTH] Request %@ has failed NTLM authentication",self);
  3063
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ has failed NTLM authentication",self);
3052 3064
 			#endif
3053 3065
 
3054 3066
 			[self failWithError:ASIAuthenticationError];
@@ -3056,7 +3068,7 @@ - (void)attemptToApplyCredentialsAndResume
3056 3068
 		} else {
3057 3069
 
3058 3070
 			#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);
  3071
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ had credentials and they were not marked as bad, but we got a 401 all the same.",self);
3060 3072
 			#endif
3061 3073
 
3062 3074
 			[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
@@ -3072,7 +3084,7 @@ - (void)attemptToApplyCredentialsAndResume
3072 3084
 		if ([self error] || [self isCancelled]) {
3073 3085
 
3074 3086
 			#if DEBUG_HTTP_AUTHENTICATION
3075  
-			NSLog(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
  3087
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
3076 3088
 			#endif
3077 3089
 
3078 3090
 			[delegateAuthenticationLock unlock];
@@ -3085,7 +3097,7 @@ - (void)attemptToApplyCredentialsAndResume
3085 3097
 			if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
3086 3098
 
3087 3099
 				#if DEBUG_HTTP_AUTHENTICATION
3088  
-				NSLog(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
  3100
+				ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
3089 3101
 				#endif
3090 3102
 
3091 3103
 				[delegateAuthenticationLock unlock];
@@ -3105,7 +3117,7 @@ - (void)attemptToApplyCredentialsAndResume
3105 3117
 				[self startRequest];
3106 3118
 			} else {
3107 3119
 				#if DEBUG_HTTP_AUTHENTICATION
3108  
-				NSLog(@"[AUTH] Request %@ failed to apply credentials",self);
  3120
+				ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to apply credentials",self);
3109 3121
 				#endif
3110 3122
 				[delegateAuthenticationLock unlock];
3111 3123
 				[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
@@ -3115,7 +3127,7 @@ - (void)attemptToApplyCredentialsAndResume
3115 3127
 		if ([self willAskDelegateForCredentials]) {
3116 3128
 
3117 3129
 			#if DEBUG_HTTP_AUTHENTICATION
3118  
-			NSLog(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
  3130
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
3119 3131
 			#endif
3120 3132
 
3121 3133
 			[delegateAuthenticationLock unlock];
@@ -3124,7 +3136,7 @@ - (void)attemptToApplyCredentialsAndResume
3124 3136
 		if ([self showAuthenticationDialog]) {
3125 3137
 
3126 3138
 			#if DEBUG_HTTP_AUTHENTICATION
3127  
-			NSLog(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
  3139
+			ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
3128 3140
 			#endif
3129 3141
 
3130 3142
 			[delegateAuthenticationLock unlock];
@@ -3132,7 +3144,7 @@ - (void)attemptToApplyCredentialsAndResume
3132 3144
 		}
3133 3145
 
3134 3146
 		#if DEBUG_HTTP_AUTHENTICATION
3135  
-		NSLog(@"[AUTH] Request %@ has no credentials to present and must give up",self);
  3147
+		ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
3136 3148
 		#endif
3137 3149
 		[delegateAuthenticationLock unlock];
3138 3150
 		[self failWithError:ASIAuthenticationError];
@@ -3159,7 +3171,7 @@ - (void)handleNetworkEvent:(CFStreamEventType)type
3159 3171
 	
3160 3172
 	if ([self complete] || [self isCancelled]) {
3161 3173
 		[[self cancelledLock] unlock];
3162  
-		[pool release];
  3174
+		[pool drain];
3163 3175
 		return;
3164 3176
 	}
3165 3177
 
@@ -3196,7 +3208,7 @@ - (void)handleNetworkEvent:(CFStreamEventType)type
3196 3208
 	}
3197 3209
 
3198 3210
 	CFRelease(self);
3199  
-	[pool release];
  3211
+	[pool drain];
3200 3212
 }
3201 3213
 
3202 3214
 - (BOOL)willAskDelegateToConfirmRedirect
@@ -3373,7 +3385,7 @@ - (void)handleStreamComplete
3373 3385
 {	
3374 3386
 
3375 3387
 #if DEBUG_REQUEST_STATUS
3376  
-	NSLog(@"[STATUS] Request %@ finished downloading data (%qu bytes)",self, [self totalBytesRead]);
  3388
+	ASI_DEBUG_LOG(@"[STATUS] Request %@ finished downloading data (%qu bytes)",self, [self totalBytesRead]);
3377 3389
 #endif
3378 3390
 	[self setStatusTimer:nil];
3379 3391
 	[self setDownloadComplete:YES];
@@ -3385,7 +3397,7 @@ - (void)handleStreamComplete
3385 3397
 	[progressLock lock];	
3386 3398
 	// Find out how much data we've uploaded so far
3387 3399
 	[self setLastBytesSent:totalBytesSent];	
3388  
-	[self setTotalBytesSent:[NSMakeCollectable([(NSNumber *)CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount) autorelease]) unsignedLongLongValue]];
  3400
+	[self setTotalBytesSent:[[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) autorelease] unsignedLongLongValue]];
3389 3401
 	[self setComplete:YES];
3390 3402
 	if (![self contentLength]) {
3391 3403
 		[self setContentLength:[self totalBytesRead]];
@@ -3471,7 +3483,7 @@ - (void)handleStreamComplete
3471 3483
 	}
3472 3484
 	#if DEBUG_PERSISTENT_CONNECTIONS
3473 3485
 	if ([self requestID]) {
3474  
-		NSLog(@"[CONNECTION] Request #%@ finished using connection #%@",[self requestID], [[self connectionInfo] objectForKey:@"id"]);
  3486
+		ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ finished using connection #%@",[self requestID], [[self connectionInfo] objectForKey:@"id"]);
3475 3487
 	}
3476 3488
 	#endif
3477 3489
 	[[self connectionInfo] removeObjectForKey:@"request"];
@@ -3507,13 +3519,16 @@ - (void)markAsFinished
3507 3519
 
3508 3520
 	// dealloc won't be called when running with GC, so we'll clean these up now
3509 3521
 	if (request) {
3510  
-		CFMakeCollectable(request);
  3522
+		CFRelease(request);
  3523
+		request = nil;
3511 3524
 	}
3512 3525
 	if (requestAuthentication) {
3513  
-		CFMakeCollectable(requestAuthentication);
  3526
+		CFRelease(requestAuthentication);
  3527
+		requestAuthentication = nil;
3514 3528
 	}
3515 3529
 	if (proxyAuthentication) {
3516  
-		CFMakeCollectable(proxyAuthentication);
  3530
+		CFRelease(proxyAuthentication);
  3531
+		proxyAuthentication = nil;
3517 3532
 	}
3518 3533
 
3519 3534
     BOOL wasInProgress = inProgress;
@@ -3609,7 +3624,7 @@ - (BOOL)retryUsingNewConnection
3609 3624
 		[self setWillRetryRequest:NO];
3610 3625
 
3611 3626
 		#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"]);
  3627
+			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 3628
 		#endif
3614 3629
 		[connectionsLock lock];
3615 3630
 		[[self connectionInfo] removeObjectForKey:@"request"];
@@ -3621,7 +3636,7 @@ - (BOOL)retryUsingNewConnection
3621 3636
 		return YES;
3622 3637
 	}
3623 3638
 	#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"]);
  3639
+		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 3640
 	#endif	
3626 3641
 	return NO;
3627 3642
 }
@@ -3629,7 +3644,7 @@ - (BOOL)retryUsingNewConnection
3629 3644
 - (void)handleStreamError
3630 3645
 
3631 3646
 {
3632  
-	NSError *underlyingError = NSMakeCollectable([(NSError *)CFReadStreamCopyError((CFReadStreamRef)[self readStream]) autorelease]);
  3647
+	NSError *underlyingError = [NSMakeCollectable(CFReadStreamCopyError((CFReadStreamRef)[self readStream])) autorelease];
3633 3648
 
3634 3649
 	if (![self error]) { // We may already have handled this error
3635 3650
 		
@@ -3807,12 +3822,12 @@ - (BOOL)configureProxies
3807 3822
 		} else {
3808 3823
 
3809 3824
 #if TARGET_OS_IPHONE
3810  
-			NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)CFNetworkCopySystemProxySettings() autorelease]);
  3825
+			NSDictionary *proxySettings = [NSMakeCollectable(CFNetworkCopySystemProxySettings()) autorelease];
3811 3826
 #else
3812  
-			NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)SCDynamicStoreCopyProxies(NULL) autorelease]);
  3827
+			NSDictionary *proxySettings = [NSMakeCollectable(SCDynamicStoreCopyProxies(NULL)) autorelease];
3813 3828
 #endif
3814 3829
 
3815  
-			proxies = NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings) autorelease]);
  3830
+			proxies = [NSMakeCollectable(CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings)) autorelease];
3816 3831
 
3817 3832
 			// 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 3833
 			NSDictionary *settings = [proxies objectAtIndex:0];
@@ -3964,7 +3979,7 @@ - (void)runPACScript:(NSString *)script
3964 3979
 
3965 3980
 		// Obtain the list of proxies by running the autoconfiguration script
3966 3981
 		CFErrorRef err = NULL;
3967  
-		NSArray *proxies = NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef)script,(CFURLRef)[self url], &err) autorelease]);
  3982
+		NSArray *proxies = [NSMakeCollectable(CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef)script,(CFURLRef)[self url], &err)) autorelease];
3968 3983
 		if (!err && [proxies count] > 0) {
3969 3984
 			NSDictionary *settings = [proxies objectAtIndex:0];
3970 3985
 			[self setProxyHost:[settings objectForKey:(NSString *)kCFProxyHostNameKey]];
@@ -4009,7 +4024,7 @@ + (void)expirePersistentConnections
4009 4024
 		NSDictionary *existingConnection = [persistentConnectionsPool objectAtIndex:i];
4010 4025
 		if (![existingConnection objectForKey:@"request"] && [[existingConnection objectForKey:@"expires"] timeIntervalSinceNow] <= 0) {
4011 4026
 #if DEBUG_PERSISTENT_CONNECTIONS
4012  
-			NSLog(@"[CONNECTION] Closing connection #%i because it has expired",[[existingConnection objectForKey:@"id"] intValue]);
  4027
+			ASI_DEBUG_LOG(@"[CONNECTION] Closing connection #%i because it has expired",[[existingConnection objectForKey:@"id"] intValue]);
4013 4028
 #endif
4014 4029
 			NSInputStream *stream = [existingConnection objectForKey:@"stream"];
4015 4030
 			if (stream) {
@@ -4023,7 +4038,6 @@ + (void)expirePersistentConnections
4023 4038
 }
4024 4039
 
4025 4040
 #pragma mark NSCopying
4026  
-
4027 4041
 - (id)copyWithZone:(NSZone *)zone
4028 4042
 {
4029 4043
 	// Don't forget - this will return a retained copy!
@@ -4078,6 +4092,7 @@ - (id)copyWithZone:(NSZone *)zone
4078 4092
 	[newRequest setShouldUseRFC2616RedirectBehaviour:[self shouldUseRFC2616RedirectBehaviour]];
4079 4093
 	[newRequest setShouldAttemptPersistentConnection:[self shouldAttemptPersistentConnection]];
4080 4094
 	[newRequest setPersistentConnectionTimeoutSeconds:[self persistentConnectionTimeoutSeconds]];
  4095
+    [newRequest setAuthenticationScheme:[self authenticationScheme]];
4081 4096
 	return newRequest;
4082 4097
 }
4083 4098
 
@@ -4232,7 +4247,7 @@ - (NSDictionary *)findSessionAuthenticationCredentials
4232 4247
 		if ([self username] && [self password]) {
4233 4248
 			NSDictionary *usernameAndPassword = [theCredentials objectForKey:@"Credentials"];
4234 4249
 			NSString *storedUsername = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername];
4235  
-			NSString *storedPassword = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername];
  4250
+			NSString *storedPassword = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword];
4236 4251
 			if (![storedUsername isEqualToString:[self username]] || ![storedPassword isEqualToString:[self password]]) {
4237 4252
 				continue;
4238 4253
 			}
@@ -4417,6 +4432,7 @@ + (NSString *)defaultUserAgentString
4417 4432
 		}
4418 4433
 		return [[defaultUserAgent retain] autorelease];
4419 4434
 	}
  4435
+	return nil;
4420 4436
 }
4421 4437
 
4422 4438
 + (void)setDefaultUserAgentString:(NSString *)agent
@@ -4445,7 +4461,7 @@ + (NSString *)mimeTypeForFileAtPath:(NSString *)path
4445 4461
 	if (!MIMEType) {
4446 4462
 		return @"application/octet-stream";
4447 4463
 	}
4448  
-    return NSMakeCollectable([(NSString *)MIMEType autorelease]);
  4464
+    return [NSMakeCollectable(MIMEType) autorelease];
4449 4465
 }
4450 4466
 
4451 4467
 #pragma mark bandwidth measurement / throttling
@@ -4464,14 +4480,14 @@ - (void)performThrottling
4464 4480
 				if ([self readStreamIsScheduled]) {
4465 4481
 					[self unscheduleReadStream];
4466 4482
 					#if DEBUG_THROTTLING
4467  
-					NSLog(@"[THROTTLING] Sleeping request %@ until after %@",self,throttleWakeUpTime);
  4483
+					ASI_DEBUG_LOG(@"[THROTTLING] Sleeping request %@ until after %@",self,throttleWakeUpTime);
4468 4484
 					#endif
4469 4485
 				}
4470 4486
 			} else {
4471 4487
 				if (![self readStreamIsScheduled]) {
4472 4488
 					[self scheduleReadStream];
4473 4489
 					#if DEBUG_THROTTLING
4474  
-					NSLog(@"[THROTTLING] Waking up request %@",self);
  4490
+					ASI_DEBUG_LOG(@"[THROTTLING] Waking up request %@",self);
4475 4491
 					#endif
4476 4492
 				}
4477 4493
 			}
@@ -4489,7 +4505,7 @@ + (BOOL)isBandwidthThrottled
4489 4505
 #if TARGET_OS_IPHONE
4490 4506
 	[bandwidthThrottlingLock lock];
4491 4507
 
4492  
-	BOOL throttle = isBandwidthThrottled || (!shouldThrottleBandwithForWWANOnly && (maxBandwidthPerSecond > 0));
  4508
+	BOOL throttle = isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond > 0));
4493 4509
 	[bandwidthThrottlingLock unlock];
4494 4510
 	return throttle;
4495 4511
 #else
@@ -4534,7 +4550,7 @@ + (void)recordBandwidthUsage
4534 4550
 		}
4535 4551
 	}
4536 4552
 	#if DEBUG_THROTTLING
4537  
-	NSLog(@"[THROTTLING] ===Used: %u bytes of bandwidth in last measurement period===",bandwidthUsedInLastSecond);
  4553
+	ASI_DEBUG_LOG(@"[THROTTLING] ===Used: %u bytes of bandwidth in last measurement period===",bandwidthUsedInLastSecond);
4538 4554
 	#endif
4539 4555
 	[bandwidthUsageTracker addObject:[NSNumber numberWithUnsignedLong:bandwidthUsedInLastSecond]];
4540 4556
 	[bandwidthMeasurementDate release];
@@ -4569,7 +4585,7 @@ + (void)measureBandwidthUsage
4569 4585
 	// Are we performing bandwidth throttling?
4570 4586
 	if (
4571 4587
 	#if TARGET_OS_IPHONE
4572  
-	isBandwidthThrottled || (!shouldThrottleBandwithForWWANOnly && (maxBandwidthPerSecond))
  4588
+	isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond))
4573 4589
 	#else
4574 4590
 	maxBandwidthPerSecond
4575 4591
 	#endif
@@ -4621,7 +4637,7 @@ + (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle
4621 4637
 		[ASIHTTPRequest setMaxBandwidthPerSecond:0];
4622 4638
 		[bandwidthThrottlingLock lock];
4623 4639
 		isBandwidthThrottled = NO;
4624  
-		shouldThrottleBandwithForWWANOnly = NO;
  4640
+		shouldThrottleBandwidthForWWANOnly = NO;
4625 4641
 		[bandwidthThrottlingLock unlock];
4626 4642
 	}
4627 4643
 }
@@ -4629,7 +4645,7 @@ + (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle
4629 4645
 + (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit
4630 4646
 {	
4631 4647
 	[bandwidthThrottlingLock lock];
4632  
-	shouldThrottleBandwithForWWANOnly = YES;
  4648
+	shouldThrottleBandwidthForWWANOnly = YES;
4633 4649
 	maxBandwidthPerSecond = limit;
4634 4650
 	[ASIHTTPRequest registerForNetworkReachabilityNotifications];	
4635 4651
 	[bandwidthThrottlingLock unlock];
@@ -4687,6 +4703,7 @@ + (void)setDefaultCache:(id <ASICacheDelegate>)cache
4687 4703
     @synchronized(self) {
4688 4704
         return [[defaultCache retain] autorelease];
4689 4705
     }
  4706
+	return nil;
4690 4707
 }
4691 4708
 
4692 4709
 
@@ -4771,7 +4788,7 @@ + (void)runRequests
4771 4788
 	while (runAlways) {
4772 4789
 		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4773 4790
 		CFRunLoopRun();
4774  
-		[pool release];
  4791
+		[pool drain];
4775 4792
 	}
4776 4793
 
4777 4794
 	// Should never be called, but anyway
@@ -4824,6 +4841,35 @@ + (NSString*)base64forData:(NSData*)theData {
4824 4841
     return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
4825 4842
 }
4826 4843
 
  4844
++ (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
  4845
+{
  4846
+	NSDictionary *responseHeaders = [request responseHeaders];
  4847
+  
  4848
+	// If we weren't given a custom max-age, lets look for one in the response headers
  4849
+	if (!maxAge) {
  4850
+		NSString *cacheControl = [[responseHeaders objectForKey:@"Cache-Control"] lowercaseString];
  4851
+		if (cacheControl) {
  4852
+			NSScanner *scanner = [NSScanner scannerWithString:cacheControl];
  4853
+			[scanner scanUpToString:@"max-age" intoString:NULL];
  4854
+			if ([scanner scanString:@"max-age" intoString:NULL]) {
  4855
+				[scanner scanString:@"=" intoString:NULL];
  4856
+				[scanner scanDouble:&maxAge];
  4857
+			}
  4858
+		}
  4859
+	}
  4860
+  
  4861
+	// RFC 2612 says max-age must override any Expires header
  4862
+	if (maxAge) {
  4863
+		return [[NSDate date] addTimeInterval:maxAge];
  4864
+	} else {
  4865
+		NSString *expires = [responseHeaders objectForKey:@"Expires"];
  4866
+		if (expires) {
  4867
+			return [ASIHTTPRequest dateFromRFC1123String:expires];
  4868
+		}
  4869
+	}
  4870
+	return nil;
  4871
+}
  4872
+
4827 4873
 // Based on hints from http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter
4828 4874
 + (NSDate *)dateFromRFC1123String:(NSString *)string
4829 4875
 {
8  ASIHTTPRequestConfig.h 100755 → 100644
@@ -11,6 +11,12 @@
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,5 +39,5 @@
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