├── .gitignore ├── LICENSE ├── README.markdown ├── SimpleBrowser.xcodeproj └── project.pbxproj └── SimpleBrowser ├── ASIHTTPRequest ├── ASIAuthenticationDialog.h ├── ASIAuthenticationDialog.m ├── ASICacheDelegate.h ├── ASIDataCompressor.h ├── ASIDataCompressor.m ├── ASIDataDecompressor.h ├── ASIDataDecompressor.m ├── ASIDownloadCache.h ├── ASIDownloadCache.m ├── ASIHTTPRequest.h ├── ASIHTTPRequest.m ├── ASIHTTPRequestConfig.h ├── ASIHTTPRequestDelegate.h ├── ASIInputStream.h ├── ASIInputStream.m ├── ASIProgressDelegate.h └── Reachability │ ├── Reachability.h │ └── Reachability.m ├── CSSParser.h ├── CSSParser.m ├── ContentParser.h ├── ContentParser.m ├── HTMLParser.h ├── HTMLParser.m ├── HTTPResponseHandler.h ├── HTTPResponseHandler.m ├── HTTPServer.h ├── HTTPServer.m ├── ProxyRequestResponseHandler.h ├── ProxyRequestResponseHandler.m ├── SimpleBrowser-Info.plist ├── SimpleBrowser-Prefix.pch ├── SimpleBrowserAppDelegate.h ├── SimpleBrowserAppDelegate.m ├── SimpleBrowserViewController.h ├── SimpleBrowserViewController.m ├── SynthesizeSingleton.h ├── en.lproj ├── InfoPlist.strings ├── MainWindow.xib └── SimpleBrowserViewController.xib └── main.m /.gitignore: -------------------------------------------------------------------------------- 1 | *xcodeproj/project.xcworkspace 2 | *xcodeproj/xcuserdata 3 | .DS_Store 4 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 All-Seeing Interactive 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in the 10 | documentation and/or other materials provided with the distribution. 11 | * Neither the name of the All-Seeing Interactive nor the 12 | names of its contributors may be used to endorse or promote products 13 | derived from this software without specific prior written permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY All-Seeing Interactive ''AS IS'' AND ANY 16 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL All-Seeing Interactive BE LIABLE FOR ANY 19 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 22 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | 26 | -- 27 | 28 | This software includes Matt Gallagher's simple Cocoa webserver, see: 29 | 30 | http://cocoawithlove.com/2009/07/simple-extensible-http-server-in-cocoa.html 31 | 32 | The following license applies to this code: 33 | 34 | Copyright Matt Gallagher 2009. All rights reserved. 35 | 36 | Permission is given to use this source code file, free of charge, in any 37 | project, commercial or otherwise, entirely at your risk, with the condition 38 | that any redistribution (in part or whole) of source code must retain 39 | this copyright and permission notice. Attribution in compiled projects is 40 | appreciated but not required. -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | # Proxying UIWebView - EXPERIMENTAL! 2 | 3 | ###What? 4 | This project demonstrates a UIWebView that proxies nearly all HTTP requests via a local web-server. 5 | 6 | ###Why? 7 | This is a replacement for my [ASIWebPageRequest class](http://allseeing-i.com/ASIHTTPRequest/ASIWebPageRequest), currently part of [ASIHTTPRequest](http://allseeing-i.com/ASIHTTPRequest). ASIWebPageRequest started with a root web page, parsed it to find the urls of external resources, then downloaded and cached each one. When the process was finished, you could take the locally cached content and display it in the webview. 8 | 9 | This allowed you to, for example: 10 | 11 | * Cache large web pages, including external resources, indefinitely on disk 12 | * Use ASIHTTPRequest features like throttling, custom proxies etc for content loaded in a UIWebView 13 | * With some tweaking you could potentially load different content for external resources 14 | 15 | This project demonstrates a different approach to the same problem. In this project, requests made by the UIWebView are sent to a local mini-webserver that downloads the remote content and returns it to the webview. 16 | 17 | ###Advantages over ASIWebPageRequest 18 | * This approach is _MUCH_ faster, partly because the WebView can begin rendering the page before it has completely loaded, but also because only the resources needed to display the page are downloaded 19 | * This approach works better with javascript because the base url of the content is changed to mimic the original web page 20 | * Though the overall class structure is a bit more complex, it should be easier to customise 21 | 22 | ###How it works 23 | 1. SimpleBrowserViewController reads the url from the address bar, then changes it to point at the local webserver. For example, a request to http://allseeing-i.com becomes http://127.0.0.1:8080/url?=http://allseeing-i.com. 24 | 2. The webserver receives the request, the forwards it on to the real destination. ASIHTTPRequest is currently used to create these requests, but with a bit of tweaking it should be easy to use NSURLConnection instead. 25 | 3. When we start to receive the response from the remote server, we look at the content type. If it looks like the content is either HTML or CSS, we wait to receive the whole thing. Otherwise, we start returning the content to the webview unmodified. 26 | 4. When we finish receiving an HTML or CSS document, we parse the contents to replace urls pointing at the remote server with urls pointing at our local webserver. Once replacement is complete, we return the content to the webview. 27 | 28 | The sample is setup to store content permanently with ASIDownloadCache for demonstration purposes. You can change this or customise the requests in other ways by modifying startRequest in ProxyRequestResponseHandler.m. 29 | 30 | 31 | ###Known issues 32 | * Not all requests are proxied via the local webserver. In particular, content loaded via javascript is loaded by the WebView directly. 33 | * Some sites don't work properly at present. For example, m.youtube.com doesn't work at all, and pages on apple.com have significant rendering artifacts. In general, it works well with sites built with well-formed, standards compliant markup that don't make heavy use of JS, and less well with other sites. 34 | * This project includes a slightly tweaked version of ASIHTTPRequest, but I haven't got around to documenting these changes or moving them into the main ASIHTTTPRequest distribution. 35 | * Libxml can get shouty in your console when it finds HTML it doesn't like 36 | 37 | ###Areas for improvement 38 | * The webserver and parsing operations currently run on the main thread. It should be fairly straightforward to move these into a background thread. 39 | * Currently only works on iOS. It should be possible to use the same approach with the WebView class on Mac. 40 | 41 | -- 42 | 43 | ###IMPORTANT 44 | This was written over a couple of weekends, and should be considered *experimental*. The code could use some cleanup. It doesn't work with all web content, and though it should be more widely compatible than ASIWebPageRequest, [many of the same limitations apply](http://allseeing-i.com/ASIHTTPRequest/ASIWebPageRequest#limitations). You should not consider this to be a drop-in replacement for UIWebView's regular loading mechanism - it will work best with pages you have tested and confirmed to work (it might be ideal for caching content created specifically for your app offline, for example). 45 | 46 | ###Acknowledgements 47 | All the hard work of handling requests from the webview is done by a slightly tweaked version of [Matt Gallagher's simple Cocoa webserver](http://cocoawithlove.com/2009/07/simple-extensible-http-server-in-cocoa.html). 48 | 49 | HTML content is parsed using [libxml](http://xmlsoft.org/). If you want to use Libxml in a Mac or iOS project, make sure you add the dylib and add this to your _Header Search Paths_ in Xcode: 50 | 51 | ${SDK_DIR}/usr/include/libxml2 52 | 53 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIAuthenticationDialog.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIAuthenticationDialog.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 21/08/2009. 6 | // Copyright 2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | @class ASIHTTPRequest; 12 | 13 | typedef enum _ASIAuthenticationType { 14 | ASIStandardAuthenticationType = 0, 15 | ASIProxyAuthenticationType = 1 16 | } ASIAuthenticationType; 17 | 18 | @interface ASIAutorotatingViewController : UIViewController 19 | @end 20 | 21 | @interface ASIAuthenticationDialog : ASIAutorotatingViewController { 22 | ASIHTTPRequest *request; 23 | ASIAuthenticationType type; 24 | UITableView *tableView; 25 | UIViewController *presentingController; 26 | BOOL didEnableRotationNotifications; 27 | } 28 | + (void)presentAuthenticationDialogForRequest:(ASIHTTPRequest *)request; 29 | + (void)dismiss; 30 | 31 | @property (retain) ASIHTTPRequest *request; 32 | @property (assign) ASIAuthenticationType type; 33 | @property (assign) BOOL didEnableRotationNotifications; 34 | @property (retain, nonatomic) UIViewController *presentingController; 35 | @end 36 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIAuthenticationDialog.m: -------------------------------------------------------------------------------- 1 | // 2 | // ASIAuthenticationDialog.m 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 21/08/2009. 6 | // Copyright 2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "ASIAuthenticationDialog.h" 10 | #import "ASIHTTPRequest.h" 11 | #import 12 | 13 | static ASIAuthenticationDialog *sharedDialog = nil; 14 | BOOL isDismissing = NO; 15 | static NSMutableArray *requestsNeedingAuthentication = nil; 16 | 17 | static const NSUInteger kUsernameRow = 0; 18 | static const NSUInteger kUsernameSection = 0; 19 | static const NSUInteger kPasswordRow = 1; 20 | static const NSUInteger kPasswordSection = 0; 21 | static const NSUInteger kDomainRow = 0; 22 | static const NSUInteger kDomainSection = 1; 23 | 24 | 25 | @implementation ASIAutorotatingViewController 26 | 27 | - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 28 | { 29 | return YES; 30 | } 31 | 32 | @end 33 | 34 | 35 | @interface ASIAuthenticationDialog () 36 | - (void)showTitle; 37 | - (void)show; 38 | - (NSArray *)requestsRequiringTheseCredentials; 39 | - (void)presentNextDialog; 40 | - (void)keyboardWillShow:(NSNotification *)notification; 41 | - (void)orientationChanged:(NSNotification *)notification; 42 | - (void)cancelAuthenticationFromDialog:(id)sender; 43 | - (void)loginWithCredentialsFromDialog:(id)sender; 44 | @property (retain) UITableView *tableView; 45 | @end 46 | 47 | @implementation ASIAuthenticationDialog 48 | 49 | #pragma mark init / dealloc 50 | 51 | + (void)initialize 52 | { 53 | if (self == [ASIAuthenticationDialog class]) { 54 | requestsNeedingAuthentication = [[NSMutableArray array] retain]; 55 | } 56 | } 57 | 58 | + (void)presentAuthenticationDialogForRequest:(ASIHTTPRequest *)theRequest 59 | { 60 | // No need for a lock here, this will always be called on the main thread 61 | if (!sharedDialog) { 62 | sharedDialog = [[self alloc] init]; 63 | [sharedDialog setRequest:theRequest]; 64 | if ([theRequest authenticationNeeded] == ASIProxyAuthenticationNeeded) { 65 | [sharedDialog setType:ASIProxyAuthenticationType]; 66 | } else { 67 | [sharedDialog setType:ASIStandardAuthenticationType]; 68 | } 69 | [sharedDialog show]; 70 | } else { 71 | [requestsNeedingAuthentication addObject:theRequest]; 72 | } 73 | } 74 | 75 | - (id)init 76 | { 77 | if ((self = [self initWithNibName:nil bundle:nil])) { 78 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 79 | 80 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 81 | if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { 82 | #endif 83 | if (![UIDevice currentDevice].generatesDeviceOrientationNotifications) { 84 | [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 85 | [self setDidEnableRotationNotifications:YES]; 86 | } 87 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; 88 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 89 | } 90 | #endif 91 | } 92 | return self; 93 | } 94 | 95 | - (void)dealloc 96 | { 97 | if ([self didEnableRotationNotifications]) { 98 | [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]; 99 | } 100 | [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; 101 | 102 | [request release]; 103 | [tableView release]; 104 | [presentingController.view removeFromSuperview]; 105 | [presentingController release]; 106 | [super dealloc]; 107 | } 108 | 109 | #pragma mark keyboard notifications 110 | 111 | - (void)keyboardWillShow:(NSNotification *)notification 112 | { 113 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 114 | if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { 115 | #endif 116 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2 117 | NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]; 118 | #else 119 | NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey]; 120 | #endif 121 | CGRect keyboardBounds; 122 | [keyboardBoundsValue getValue:&keyboardBounds]; 123 | UIEdgeInsets e = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0); 124 | [[self tableView] setScrollIndicatorInsets:e]; 125 | [[self tableView] setContentInset:e]; 126 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 127 | } 128 | #endif 129 | } 130 | 131 | // Manually handles orientation changes on iPhone 132 | - (void)orientationChanged:(NSNotification *)notification 133 | { 134 | [self showTitle]; 135 | 136 | UIInterfaceOrientation o = (UIInterfaceOrientation)[[UIApplication sharedApplication] statusBarOrientation]; 137 | CGFloat angle = 0; 138 | switch (o) { 139 | case UIDeviceOrientationLandscapeLeft: angle = 90; break; 140 | case UIDeviceOrientationLandscapeRight: angle = -90; break; 141 | case UIDeviceOrientationPortraitUpsideDown: angle = 180; break; 142 | default: break; 143 | } 144 | 145 | CGRect f = [[UIScreen mainScreen] applicationFrame]; 146 | 147 | // Swap the frame height and width if necessary 148 | if (UIDeviceOrientationIsLandscape(o)) { 149 | CGFloat t; 150 | t = f.size.width; 151 | f.size.width = f.size.height; 152 | f.size.height = t; 153 | } 154 | 155 | CGAffineTransform previousTransform = self.view.layer.affineTransform; 156 | CGAffineTransform newTransform = CGAffineTransformMakeRotation((CGFloat)(angle * M_PI / 180.0)); 157 | 158 | // Reset the transform so we can set the size 159 | self.view.layer.affineTransform = CGAffineTransformIdentity; 160 | self.view.frame = (CGRect){ { 0, 0 }, f.size}; 161 | 162 | // Revert to the previous transform for correct animation 163 | self.view.layer.affineTransform = previousTransform; 164 | 165 | [UIView beginAnimations:nil context:NULL]; 166 | [UIView setAnimationDuration:0.3]; 167 | 168 | // Set the new transform 169 | self.view.layer.affineTransform = newTransform; 170 | 171 | // Fix the view origin 172 | self.view.frame = (CGRect){ { f.origin.x, f.origin.y },self.view.frame.size}; 173 | [UIView commitAnimations]; 174 | } 175 | 176 | #pragma mark utilities 177 | 178 | - (UIViewController *)presentingController 179 | { 180 | if (!presentingController) { 181 | presentingController = [[ASIAutorotatingViewController alloc] initWithNibName:nil bundle:nil]; 182 | 183 | // Attach to the window, but don't interfere. 184 | UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0]; 185 | [window addSubview:[presentingController view]]; 186 | [[presentingController view] setFrame:CGRectZero]; 187 | [[presentingController view] setUserInteractionEnabled:NO]; 188 | } 189 | 190 | return presentingController; 191 | } 192 | 193 | - (UITextField *)textFieldInRow:(NSUInteger)row section:(NSUInteger)section 194 | { 195 | return [[[[[self tableView] cellForRowAtIndexPath: 196 | [NSIndexPath indexPathForRow:row inSection:section]] 197 | contentView] subviews] objectAtIndex:0]; 198 | } 199 | 200 | - (UITextField *)usernameField 201 | { 202 | return [self textFieldInRow:kUsernameRow section:kUsernameSection]; 203 | } 204 | 205 | - (UITextField *)passwordField 206 | { 207 | return [self textFieldInRow:kPasswordRow section:kPasswordSection]; 208 | } 209 | 210 | - (UITextField *)domainField 211 | { 212 | return [self textFieldInRow:kDomainRow section:kDomainSection]; 213 | } 214 | 215 | #pragma mark show / dismiss 216 | 217 | + (void)dismiss 218 | { 219 | [[sharedDialog parentViewController] dismissModalViewControllerAnimated:YES]; 220 | } 221 | 222 | - (void)viewDidDisappear:(BOOL)animated 223 | { 224 | [self retain]; 225 | [sharedDialog release]; 226 | sharedDialog = nil; 227 | [self performSelector:@selector(presentNextDialog) withObject:nil afterDelay:0]; 228 | [self release]; 229 | } 230 | 231 | - (void)dismiss 232 | { 233 | if (self == sharedDialog) { 234 | [[self class] dismiss]; 235 | } else { 236 | [[self parentViewController] dismissModalViewControllerAnimated:YES]; 237 | } 238 | } 239 | 240 | - (void)showTitle 241 | { 242 | UINavigationBar *navigationBar = [[[self view] subviews] objectAtIndex:0]; 243 | UINavigationItem *navItem = [[navigationBar items] objectAtIndex:0]; 244 | if (UIInterfaceOrientationIsPortrait([[UIDevice currentDevice] orientation])) { 245 | // Setup the title 246 | if ([self type] == ASIProxyAuthenticationType) { 247 | [navItem setPrompt:@"Login to this secure proxy server."]; 248 | } else { 249 | [navItem setPrompt:@"Login to this secure server."]; 250 | } 251 | } else { 252 | [navItem setPrompt:nil]; 253 | } 254 | [navigationBar sizeToFit]; 255 | CGRect f = [[self view] bounds]; 256 | f.origin.y = [navigationBar frame].size.height; 257 | f.size.height -= f.origin.y; 258 | [[self tableView] setFrame:f]; 259 | } 260 | 261 | - (void)show 262 | { 263 | // Remove all subviews 264 | UIView *v; 265 | while ((v = [[[self view] subviews] lastObject])) { 266 | [v removeFromSuperview]; 267 | } 268 | 269 | // Setup toolbar 270 | UINavigationBar *bar = [[[UINavigationBar alloc] init] autorelease]; 271 | [bar setAutoresizingMask:UIViewAutoresizingFlexibleWidth]; 272 | 273 | UINavigationItem *navItem = [[[UINavigationItem alloc] init] autorelease]; 274 | bar.items = [NSArray arrayWithObject:navItem]; 275 | 276 | [[self view] addSubview:bar]; 277 | 278 | [self showTitle]; 279 | 280 | // Setup toolbar buttons 281 | if ([self type] == ASIProxyAuthenticationType) { 282 | [navItem setTitle:[[self request] proxyHost]]; 283 | } else { 284 | [navItem setTitle:[[[self request] url] host]]; 285 | } 286 | 287 | [navItem setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelAuthenticationFromDialog:)] autorelease]]; 288 | [navItem setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"Login" style:UIBarButtonItemStyleDone target:self action:@selector(loginWithCredentialsFromDialog:)] autorelease]]; 289 | 290 | // We show the login form in a table view, similar to Safari's authentication dialog 291 | [bar sizeToFit]; 292 | CGRect f = [[self view] bounds]; 293 | f.origin.y = [bar frame].size.height; 294 | f.size.height -= f.origin.y; 295 | 296 | [self setTableView:[[[UITableView alloc] initWithFrame:f style:UITableViewStyleGrouped] autorelease]]; 297 | [[self tableView] setDelegate:self]; 298 | [[self tableView] setDataSource:self]; 299 | [[self tableView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; 300 | [[self view] addSubview:[self tableView]]; 301 | 302 | // Force reload the table content, and focus the first field to show the keyboard 303 | [[self tableView] reloadData]; 304 | [[[[[self tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]].contentView subviews] objectAtIndex:0] becomeFirstResponder]; 305 | 306 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 307 | if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { 308 | [self setModalPresentationStyle:UIModalPresentationFormSheet]; 309 | } 310 | #endif 311 | 312 | [[self presentingController] presentModalViewController:self animated:YES]; 313 | } 314 | 315 | #pragma mark button callbacks 316 | 317 | - (void)cancelAuthenticationFromDialog:(id)sender 318 | { 319 | for (ASIHTTPRequest *theRequest in [self requestsRequiringTheseCredentials]) { 320 | [theRequest cancelAuthentication]; 321 | [requestsNeedingAuthentication removeObject:theRequest]; 322 | } 323 | [self dismiss]; 324 | } 325 | 326 | - (NSArray *)requestsRequiringTheseCredentials 327 | { 328 | NSMutableArray *requestsRequiringTheseCredentials = [NSMutableArray array]; 329 | NSURL *requestURL = [[self request] url]; 330 | for (ASIHTTPRequest *otherRequest in requestsNeedingAuthentication) { 331 | NSURL *theURL = [otherRequest url]; 332 | if (([otherRequest authenticationNeeded] == [[self request] authenticationNeeded]) && [[theURL host] isEqualToString:[requestURL host]] && ([theURL port] == [requestURL port] || ([requestURL port] && [[theURL port] isEqualToNumber:[requestURL port]])) && [[theURL scheme] isEqualToString:[requestURL scheme]] && ((![otherRequest authenticationRealm] && ![[self request] authenticationRealm]) || ([otherRequest authenticationRealm] && [[self request] authenticationRealm] && [[[self request] authenticationRealm] isEqualToString:[otherRequest authenticationRealm]]))) { 333 | [requestsRequiringTheseCredentials addObject:otherRequest]; 334 | } 335 | } 336 | [requestsRequiringTheseCredentials addObject:[self request]]; 337 | return requestsRequiringTheseCredentials; 338 | } 339 | 340 | - (void)presentNextDialog 341 | { 342 | if ([requestsNeedingAuthentication count]) { 343 | ASIHTTPRequest *nextRequest = [requestsNeedingAuthentication objectAtIndex:0]; 344 | [requestsNeedingAuthentication removeObjectAtIndex:0]; 345 | [[self class] presentAuthenticationDialogForRequest:nextRequest]; 346 | } 347 | } 348 | 349 | 350 | - (void)loginWithCredentialsFromDialog:(id)sender 351 | { 352 | for (ASIHTTPRequest *theRequest in [self requestsRequiringTheseCredentials]) { 353 | 354 | NSString *username = [[self usernameField] text]; 355 | NSString *password = [[self passwordField] text]; 356 | 357 | if (username == nil) { username = @""; } 358 | if (password == nil) { password = @""; } 359 | 360 | if ([self type] == ASIProxyAuthenticationType) { 361 | [theRequest setProxyUsername:username]; 362 | [theRequest setProxyPassword:password]; 363 | } else { 364 | [theRequest setUsername:username]; 365 | [theRequest setPassword:password]; 366 | } 367 | 368 | // Handle NTLM domains 369 | NSString *scheme = ([self type] == ASIStandardAuthenticationType) ? [[self request] authenticationScheme] : [[self request] proxyAuthenticationScheme]; 370 | if ([scheme isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeNTLM]) { 371 | NSString *domain = [[self domainField] text]; 372 | if ([self type] == ASIProxyAuthenticationType) { 373 | [theRequest setProxyDomain:domain]; 374 | } else { 375 | [theRequest setDomain:domain]; 376 | } 377 | } 378 | 379 | [theRequest retryUsingSuppliedCredentials]; 380 | [requestsNeedingAuthentication removeObject:theRequest]; 381 | } 382 | [self dismiss]; 383 | } 384 | 385 | #pragma mark table view data source 386 | 387 | - (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView 388 | { 389 | NSString *scheme = ([self type] == ASIStandardAuthenticationType) ? [[self request] authenticationScheme] : [[self request] proxyAuthenticationScheme]; 390 | if ([scheme isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeNTLM]) { 391 | return 2; 392 | } 393 | return 1; 394 | } 395 | 396 | - (CGFloat)tableView:(UITableView *)aTableView heightForFooterInSection:(NSInteger)section 397 | { 398 | if (section == [self numberOfSectionsInTableView:aTableView]-1) { 399 | return 30; 400 | } 401 | return 0; 402 | } 403 | 404 | - (CGFloat)tableView:(UITableView *)aTableView heightForHeaderInSection:(NSInteger)section 405 | { 406 | if (section == 0) { 407 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 408 | if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { 409 | return 54; 410 | } 411 | #endif 412 | return 30; 413 | } 414 | return 0; 415 | } 416 | 417 | - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 418 | { 419 | if (section == 0) { 420 | return [[self request] authenticationRealm]; 421 | } 422 | return nil; 423 | } 424 | 425 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 426 | { 427 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_0 428 | UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease]; 429 | #else 430 | UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0,0,0,0) reuseIdentifier:nil] autorelease]; 431 | #endif 432 | 433 | [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 434 | 435 | CGRect f = CGRectInset([cell bounds], 10, 10); 436 | UITextField *textField = [[[UITextField alloc] initWithFrame:f] autorelease]; 437 | [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; 438 | [textField setAutocapitalizationType:UITextAutocapitalizationTypeNone]; 439 | [textField setAutocorrectionType:UITextAutocorrectionTypeNo]; 440 | 441 | NSUInteger s = [indexPath section]; 442 | NSUInteger r = [indexPath row]; 443 | 444 | if (s == kUsernameSection && r == kUsernameRow) { 445 | [textField setPlaceholder:@"User"]; 446 | } else if (s == kPasswordSection && r == kPasswordRow) { 447 | [textField setPlaceholder:@"Password"]; 448 | [textField setSecureTextEntry:YES]; 449 | } else if (s == kDomainSection && r == kDomainRow) { 450 | [textField setPlaceholder:@"Domain"]; 451 | } 452 | [cell.contentView addSubview:textField]; 453 | 454 | return cell; 455 | } 456 | 457 | - (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section 458 | { 459 | if (section == 0) { 460 | return 2; 461 | } else { 462 | return 1; 463 | } 464 | } 465 | 466 | - (NSString *)tableView:(UITableView *)aTableView titleForFooterInSection:(NSInteger)section 467 | { 468 | if (section == [self numberOfSectionsInTableView:aTableView]-1) { 469 | // If we're using Basic authentication and the connection is not using SSL, we'll show the plain text message 470 | if ([[[self request] authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic] && ![[[[self request] url] scheme] isEqualToString:@"https"]) { 471 | return @"Password will be sent in the clear."; 472 | // We are using Digest, NTLM, or any scheme over SSL 473 | } else { 474 | return @"Password will be sent securely."; 475 | } 476 | } 477 | return nil; 478 | } 479 | 480 | #pragma mark - 481 | 482 | @synthesize request; 483 | @synthesize type; 484 | @synthesize tableView; 485 | @synthesize didEnableRotationNotifications; 486 | @synthesize presentingController; 487 | @end 488 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASICacheDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASICacheDelegate.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 01/05/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import 10 | @class ASIHTTPRequest; 11 | 12 | // Cache policies control the behaviour of a cache and how requests use the cache 13 | // When setting a cache policy, you can use a combination of these values as a bitmask 14 | // For example: [request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy|ASIDoNotWriteToCacheCachePolicy]; 15 | // Note that some of the behaviours below are mutally exclusive - you cannot combine ASIAskServerIfModifiedWhenStaleCachePolicy and ASIAskServerIfModifiedCachePolicy, for example. 16 | typedef enum _ASICachePolicy { 17 | 18 | // The default cache policy. When you set a request to use this, it will use the cache's defaultCachePolicy 19 | // ASIDownloadCache's default cache policy is 'ASIAskServerIfModifiedWhenStaleCachePolicy' 20 | ASIUseDefaultCachePolicy = 0, 21 | 22 | // Tell the request not to read from the cache 23 | ASIDoNotReadFromCacheCachePolicy = 1, 24 | 25 | // The the request not to write to the cache 26 | ASIDoNotWriteToCacheCachePolicy = 2, 27 | 28 | // Ask the server if there is an updated version of this resource (using a conditional GET) ONLY when the cached data is stale 29 | ASIAskServerIfModifiedWhenStaleCachePolicy = 4, 30 | 31 | // Always ask the server if there is an updated version of this resource (using a conditional GET) 32 | ASIAskServerIfModifiedCachePolicy = 8, 33 | 34 | // If cached data exists, use it even if it is stale. This means requests will not talk to the server unless the resource they are requesting is not in the cache 35 | ASIOnlyLoadIfNotCachedCachePolicy = 16, 36 | 37 | // If cached data exists, use it even if it is stale. If cached data does not exist, stop (will not set an error on the request) 38 | ASIDontLoadCachePolicy = 32, 39 | 40 | // Specifies that cached data may be used if the request fails. If cached data is used, the request will succeed without error. Usually used in combination with other options above. 41 | ASIFallbackToCacheIfLoadFailsCachePolicy = 64 42 | } ASICachePolicy; 43 | 44 | // Cache storage policies control whether cached data persists between application launches (ASICachePermanentlyCacheStoragePolicy) or not (ASICacheForSessionDurationCacheStoragePolicy) 45 | // Calling [ASIHTTPRequest clearSession] will remove any data stored using ASICacheForSessionDurationCacheStoragePolicy 46 | typedef enum _ASICacheStoragePolicy { 47 | ASICacheForSessionDurationCacheStoragePolicy = 0, 48 | ASICachePermanentlyCacheStoragePolicy = 1 49 | } ASICacheStoragePolicy; 50 | 51 | 52 | @protocol ASICacheDelegate 53 | 54 | @required 55 | 56 | // Should return the cache policy that will be used when requests have their cache policy set to ASIUseDefaultCachePolicy 57 | - (ASICachePolicy)defaultCachePolicy; 58 | 59 | // Returns the date a cached response should expire on. Pass a non-zero max age to specify a custom date. 60 | - (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge; 61 | 62 | // Updates cached response headers with a new expiry date. Pass a non-zero max age to specify a custom date. 63 | - (void)updateExpiryForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge; 64 | 65 | // Looks at the request's cache policy and any cached headers to determine if the cache data is still valid 66 | - (BOOL)canUseCachedDataForRequest:(ASIHTTPRequest *)request; 67 | 68 | // Removes cached data for a particular request 69 | - (void)removeCachedDataForRequest:(ASIHTTPRequest *)request; 70 | 71 | // Should return YES if the cache considers its cached response current for the request 72 | // Should return NO is the data is not cached, or (for example) if the cached headers state the request should have expired 73 | - (BOOL)isCachedDataCurrentForRequest:(ASIHTTPRequest *)request; 74 | 75 | // Should store the response for the passed request in the cache 76 | // When a non-zero maxAge is passed, it should be used as the expiry time for the cached response 77 | - (void)storeResponseForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge; 78 | 79 | // Removes cached data for a particular url 80 | - (void)removeCachedDataForURL:(NSURL *)url; 81 | 82 | // Should return an NSDictionary of cached headers for the passed URL, if it is stored in the cache 83 | - (NSDictionary *)cachedResponseHeadersForURL:(NSURL *)url; 84 | 85 | // Should return the cached body of a response for the passed URL, if it is stored in the cache 86 | - (NSData *)cachedResponseDataForURL:(NSURL *)url; 87 | 88 | // Returns a path to the cached response data, if it exists 89 | - (NSString *)pathToCachedResponseDataForURL:(NSURL *)url; 90 | 91 | // Returns a path to the cached response headers, if they url 92 | - (NSString *)pathToCachedResponseHeadersForURL:(NSURL *)url; 93 | 94 | // Returns the location to use to store cached response headers for a particular request 95 | - (NSString *)pathToStoreCachedResponseHeadersForRequest:(ASIHTTPRequest *)request; 96 | 97 | // Returns the location to use to store a cached response body for a particular request 98 | - (NSString *)pathToStoreCachedResponseDataForRequest:(ASIHTTPRequest *)request; 99 | 100 | // Clear cached data stored for the passed storage policy 101 | - (void)clearCachedResponsesForStoragePolicy:(ASICacheStoragePolicy)cachePolicy; 102 | 103 | @end 104 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIDataCompressor.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIDataCompressor.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 17/08/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | // This is a helper class used by ASIHTTPRequest to handle deflating (compressing) data in memory and on disk 10 | // You may also find it helpful if you need to deflate data and files yourself - see the class methods below 11 | // Most of the zlib stuff is based on the sample code by Mark Adler available at http://zlib.net 12 | 13 | #import 14 | #import 15 | 16 | @interface ASIDataCompressor : NSObject { 17 | BOOL streamReady; 18 | z_stream zStream; 19 | } 20 | 21 | // Convenience constructor will call setupStream for you 22 | + (id)compressor; 23 | 24 | // Compress the passed chunk of data 25 | // Passing YES for shouldFinish will finalize the deflated data - you must pass YES when you are on the last chunk of data 26 | - (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err shouldFinish:(BOOL)shouldFinish; 27 | 28 | // Convenience method - pass it some data, and you'll get deflated data back 29 | + (NSData *)compressData:(NSData*)uncompressedData error:(NSError **)err; 30 | 31 | // Convenience method - pass it a file containing the data to compress in sourcePath, and it will write deflated data to destinationPath 32 | + (BOOL)compressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err; 33 | 34 | // Sets up zlib to handle the inflating. You only need to call this yourself if you aren't using the convenience constructor 'compressor' 35 | - (NSError *)setupStream; 36 | 37 | // Tells zlib to clean up. You need to call this if you need to cancel deflating part way through 38 | // If deflating finishes or fails, this method will be called automatically 39 | - (NSError *)closeStream; 40 | 41 | @property (assign, readonly) BOOL streamReady; 42 | @end 43 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIDataCompressor.m: -------------------------------------------------------------------------------- 1 | // 2 | // ASIDataCompressor.m 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 17/08/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "ASIDataCompressor.h" 10 | #import "ASIHTTPRequest.h" 11 | 12 | #define DATA_CHUNK_SIZE 262144 // Deal with gzipped data in 256KB chunks 13 | #define COMPRESSION_AMOUNT Z_DEFAULT_COMPRESSION 14 | 15 | @interface ASIDataCompressor () 16 | + (NSError *)deflateErrorWithCode:(int)code; 17 | @end 18 | 19 | @implementation ASIDataCompressor 20 | 21 | + (id)compressor 22 | { 23 | ASIDataCompressor *compressor = [[[self alloc] init] autorelease]; 24 | [compressor setupStream]; 25 | return compressor; 26 | } 27 | 28 | - (void)dealloc 29 | { 30 | if (streamReady) { 31 | [self closeStream]; 32 | } 33 | [super dealloc]; 34 | } 35 | 36 | - (NSError *)setupStream 37 | { 38 | if (streamReady) { 39 | return nil; 40 | } 41 | // Setup the inflate stream 42 | zStream.zalloc = Z_NULL; 43 | zStream.zfree = Z_NULL; 44 | zStream.opaque = Z_NULL; 45 | zStream.avail_in = 0; 46 | zStream.next_in = 0; 47 | int status = deflateInit2(&zStream, COMPRESSION_AMOUNT, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY); 48 | if (status != Z_OK) { 49 | return [[self class] deflateErrorWithCode:status]; 50 | } 51 | streamReady = YES; 52 | return nil; 53 | } 54 | 55 | - (NSError *)closeStream 56 | { 57 | if (!streamReady) { 58 | return nil; 59 | } 60 | // Close the deflate stream 61 | streamReady = NO; 62 | int status = deflateEnd(&zStream); 63 | if (status != Z_OK) { 64 | return [[self class] deflateErrorWithCode:status]; 65 | } 66 | return nil; 67 | } 68 | 69 | - (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err shouldFinish:(BOOL)shouldFinish 70 | { 71 | if (length == 0) return nil; 72 | 73 | NSUInteger halfLength = length/2; 74 | 75 | // We'll take a guess that the compressed data will fit in half the size of the original (ie the max to compress at once is half DATA_CHUNK_SIZE), if not, we'll increase it below 76 | NSMutableData *outputData = [NSMutableData dataWithLength:length/2]; 77 | 78 | int status; 79 | 80 | zStream.next_in = bytes; 81 | zStream.avail_in = (unsigned int)length; 82 | zStream.avail_out = 0; 83 | 84 | NSInteger bytesProcessedAlready = zStream.total_out; 85 | while (zStream.avail_out == 0) { 86 | 87 | if (zStream.total_out-bytesProcessedAlready >= [outputData length]) { 88 | [outputData increaseLengthBy:halfLength]; 89 | } 90 | 91 | zStream.next_out = [outputData mutableBytes] + zStream.total_out-bytesProcessedAlready; 92 | zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready)); 93 | status = deflate(&zStream, shouldFinish ? Z_FINISH : Z_NO_FLUSH); 94 | 95 | if (status == Z_STREAM_END) { 96 | break; 97 | } else if (status != Z_OK) { 98 | if (err) { 99 | *err = [[self class] deflateErrorWithCode:status]; 100 | } 101 | return NO; 102 | } 103 | } 104 | 105 | // Set real length 106 | [outputData setLength: zStream.total_out-bytesProcessedAlready]; 107 | return outputData; 108 | } 109 | 110 | 111 | + (NSData *)compressData:(NSData*)uncompressedData error:(NSError **)err 112 | { 113 | NSError *theError = nil; 114 | NSData *outputData = [[ASIDataCompressor compressor] compressBytes:(Bytef *)[uncompressedData bytes] length:[uncompressedData length] error:&theError shouldFinish:YES]; 115 | if (theError) { 116 | if (err) { 117 | *err = theError; 118 | } 119 | return nil; 120 | } 121 | return outputData; 122 | } 123 | 124 | 125 | 126 | + (BOOL)compressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err 127 | { 128 | NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; 129 | 130 | // Create an empty file at the destination path 131 | if (![fileManager createFileAtPath:destinationPath contents:[NSData data] attributes:nil]) { 132 | if (err) { 133 | *err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed because we were to create a file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,nil]]; 134 | } 135 | return NO; 136 | } 137 | 138 | // Ensure the source file exists 139 | if (![fileManager fileExistsAtPath:sourcePath]) { 140 | if (err) { 141 | *err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed the file does not exist",sourcePath],NSLocalizedDescriptionKey,nil]]; 142 | } 143 | return NO; 144 | } 145 | 146 | UInt8 inputData[DATA_CHUNK_SIZE]; 147 | NSData *outputData; 148 | NSInteger readLength; 149 | NSError *theError = nil; 150 | 151 | ASIDataCompressor *compressor = [ASIDataCompressor compressor]; 152 | 153 | NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:sourcePath]; 154 | [inputStream open]; 155 | NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO]; 156 | [outputStream open]; 157 | 158 | while ([compressor streamReady]) { 159 | 160 | // Read some data from the file 161 | readLength = [inputStream read:inputData maxLength:DATA_CHUNK_SIZE]; 162 | 163 | // Make sure nothing went wrong 164 | if ([inputStream streamStatus] == NSStreamEventErrorOccurred) { 165 | if (err) { 166 | *err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed because we were unable to read from the source data file",sourcePath],NSLocalizedDescriptionKey,[inputStream streamError],NSUnderlyingErrorKey,nil]]; 167 | } 168 | [compressor closeStream]; 169 | return NO; 170 | } 171 | // Have we reached the end of the input data? 172 | if (!readLength) { 173 | break; 174 | } 175 | 176 | // Attempt to deflate the chunk of data 177 | outputData = [compressor compressBytes:inputData length:readLength error:&theError shouldFinish:readLength < DATA_CHUNK_SIZE ]; 178 | if (theError) { 179 | if (err) { 180 | *err = theError; 181 | } 182 | [compressor closeStream]; 183 | return NO; 184 | } 185 | 186 | // Write the deflated data out to the destination file 187 | [outputStream write:[outputData bytes] maxLength:[outputData length]]; 188 | 189 | // Make sure nothing went wrong 190 | if ([inputStream streamStatus] == NSStreamEventErrorOccurred) { 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]]; 193 | } 194 | [compressor closeStream]; 195 | return NO; 196 | } 197 | 198 | } 199 | [inputStream close]; 200 | [outputStream close]; 201 | 202 | NSError *error = [compressor closeStream]; 203 | if (error) { 204 | if (err) { 205 | *err = error; 206 | } 207 | return NO; 208 | } 209 | 210 | return YES; 211 | } 212 | 213 | + (NSError *)deflateErrorWithCode:(int)code 214 | { 215 | return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of data failed with code %hi",code],NSLocalizedDescriptionKey,nil]]; 216 | } 217 | 218 | @synthesize streamReady; 219 | @end 220 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIDataDecompressor.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIDataDecompressor.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 17/08/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | // This is a helper class used by ASIHTTPRequest to handle inflating (decompressing) data in memory and on disk 10 | // You may also find it helpful if you need to inflate data and files yourself - see the class methods below 11 | // Most of the zlib stuff is based on the sample code by Mark Adler available at http://zlib.net 12 | 13 | #import 14 | #import 15 | 16 | @interface ASIDataDecompressor : NSObject { 17 | BOOL streamReady; 18 | z_stream zStream; 19 | } 20 | 21 | // Convenience constructor will call setupStream for you 22 | + (id)decompressor; 23 | 24 | // Uncompress the passed chunk of data 25 | - (NSData *)uncompressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err; 26 | 27 | // Convenience method - pass it some deflated data, and you'll get inflated data back 28 | + (NSData *)uncompressData:(NSData*)compressedData error:(NSError **)err; 29 | 30 | // Convenience method - pass it a file containing deflated data in sourcePath, and it will write inflated data to destinationPath 31 | + (BOOL)uncompressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err; 32 | 33 | // Sets up zlib to handle the inflating. You only need to call this yourself if you aren't using the convenience constructor 'decompressor' 34 | - (NSError *)setupStream; 35 | 36 | // Tells zlib to clean up. You need to call this if you need to cancel inflating part way through 37 | // If inflating finishes or fails, this method will be called automatically 38 | - (NSError *)closeStream; 39 | 40 | @property (assign, readonly) BOOL streamReady; 41 | @end 42 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIDataDecompressor.m: -------------------------------------------------------------------------------- 1 | // 2 | // ASIDataDecompressor.m 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 17/08/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "ASIDataDecompressor.h" 10 | #import "ASIHTTPRequest.h" 11 | 12 | #define DATA_CHUNK_SIZE 262144 // Deal with gzipped data in 256KB chunks 13 | 14 | @interface ASIDataDecompressor () 15 | + (NSError *)inflateErrorWithCode:(int)code; 16 | @end; 17 | 18 | @implementation ASIDataDecompressor 19 | 20 | + (id)decompressor 21 | { 22 | ASIDataDecompressor *decompressor = [[[self alloc] init] autorelease]; 23 | [decompressor setupStream]; 24 | return decompressor; 25 | } 26 | 27 | - (void)dealloc 28 | { 29 | if (streamReady) { 30 | [self closeStream]; 31 | } 32 | [super dealloc]; 33 | } 34 | 35 | - (NSError *)setupStream 36 | { 37 | if (streamReady) { 38 | return nil; 39 | } 40 | // Setup the inflate stream 41 | zStream.zalloc = Z_NULL; 42 | zStream.zfree = Z_NULL; 43 | zStream.opaque = Z_NULL; 44 | zStream.avail_in = 0; 45 | zStream.next_in = 0; 46 | int status = inflateInit2(&zStream, (15+32)); 47 | if (status != Z_OK) { 48 | return [[self class] inflateErrorWithCode:status]; 49 | } 50 | streamReady = YES; 51 | return nil; 52 | } 53 | 54 | - (NSError *)closeStream 55 | { 56 | if (!streamReady) { 57 | return nil; 58 | } 59 | // Close the inflate stream 60 | streamReady = NO; 61 | int status = inflateEnd(&zStream); 62 | if (status != Z_OK) { 63 | return [[self class] inflateErrorWithCode:status]; 64 | } 65 | return nil; 66 | } 67 | 68 | - (NSData *)uncompressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err 69 | { 70 | if (length == 0) return nil; 71 | 72 | NSUInteger halfLength = length/2; 73 | NSMutableData *outputData = [NSMutableData dataWithLength:length+halfLength]; 74 | 75 | int status; 76 | 77 | zStream.next_in = bytes; 78 | zStream.avail_in = (unsigned int)length; 79 | zStream.avail_out = 0; 80 | 81 | NSInteger bytesProcessedAlready = zStream.total_out; 82 | while (zStream.avail_in != 0) { 83 | 84 | if (zStream.total_out-bytesProcessedAlready >= [outputData length]) { 85 | [outputData increaseLengthBy:halfLength]; 86 | } 87 | 88 | zStream.next_out = [outputData mutableBytes] + zStream.total_out-bytesProcessedAlready; 89 | zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready)); 90 | 91 | status = inflate(&zStream, Z_NO_FLUSH); 92 | 93 | if (status == Z_STREAM_END) { 94 | break; 95 | } else if (status != Z_OK) { 96 | if (err) { 97 | *err = [[self class] inflateErrorWithCode:status]; 98 | } 99 | return nil; 100 | } 101 | } 102 | 103 | // Set real length 104 | [outputData setLength: zStream.total_out-bytesProcessedAlready]; 105 | return outputData; 106 | } 107 | 108 | 109 | + (NSData *)uncompressData:(NSData*)compressedData error:(NSError **)err 110 | { 111 | NSError *theError = nil; 112 | NSData *outputData = [[ASIDataDecompressor decompressor] uncompressBytes:(Bytef *)[compressedData bytes] length:[compressedData length] error:&theError]; 113 | if (theError) { 114 | if (err) { 115 | *err = theError; 116 | } 117 | return nil; 118 | } 119 | return outputData; 120 | } 121 | 122 | + (BOOL)uncompressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err 123 | { 124 | NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; 125 | 126 | // Create an empty file at the destination path 127 | if (![fileManager createFileAtPath:destinationPath contents:[NSData data] attributes:nil]) { 128 | if (err) { 129 | *err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed because we were to create a file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,nil]]; 130 | } 131 | return NO; 132 | } 133 | 134 | // Ensure the source file exists 135 | if (![fileManager fileExistsAtPath:sourcePath]) { 136 | if (err) { 137 | *err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed the file does not exist",sourcePath],NSLocalizedDescriptionKey,nil]]; 138 | } 139 | return NO; 140 | } 141 | 142 | UInt8 inputData[DATA_CHUNK_SIZE]; 143 | NSData *outputData; 144 | NSInteger readLength; 145 | NSError *theError = nil; 146 | 147 | 148 | ASIDataDecompressor *decompressor = [ASIDataDecompressor decompressor]; 149 | 150 | NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:sourcePath]; 151 | [inputStream open]; 152 | NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO]; 153 | [outputStream open]; 154 | 155 | while ([decompressor streamReady]) { 156 | 157 | // Read some data from the file 158 | readLength = [inputStream read:inputData maxLength:DATA_CHUNK_SIZE]; 159 | 160 | // Make sure nothing went wrong 161 | if ([inputStream streamStatus] == NSStreamEventErrorOccurred) { 162 | if (err) { 163 | *err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed because we were unable to read from the source data file",sourcePath],NSLocalizedDescriptionKey,[inputStream streamError],NSUnderlyingErrorKey,nil]]; 164 | } 165 | [decompressor closeStream]; 166 | return NO; 167 | } 168 | // Have we reached the end of the input data? 169 | if (!readLength) { 170 | break; 171 | } 172 | 173 | // Attempt to inflate the chunk of data 174 | outputData = [decompressor uncompressBytes:inputData length:readLength error:&theError]; 175 | if (theError) { 176 | if (err) { 177 | *err = theError; 178 | } 179 | [decompressor closeStream]; 180 | return NO; 181 | } 182 | 183 | // Write the inflated data out to the destination file 184 | [outputStream write:[outputData bytes] maxLength:[outputData length]]; 185 | 186 | // Make sure nothing went wrong 187 | if ([inputStream streamStatus] == NSStreamEventErrorOccurred) { 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]]; 190 | } 191 | [decompressor closeStream]; 192 | return NO; 193 | } 194 | 195 | } 196 | 197 | [inputStream close]; 198 | [outputStream close]; 199 | 200 | NSError *error = [decompressor closeStream]; 201 | if (error) { 202 | if (err) { 203 | *err = error; 204 | } 205 | return NO; 206 | } 207 | 208 | return YES; 209 | } 210 | 211 | 212 | + (NSError *)inflateErrorWithCode:(int)code 213 | { 214 | return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of data failed with code %hi",code],NSLocalizedDescriptionKey,nil]]; 215 | } 216 | 217 | @synthesize streamReady; 218 | @end 219 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIDownloadCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIDownloadCache.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 01/05/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "ASICacheDelegate.h" 11 | 12 | @interface ASIDownloadCache : NSObject { 13 | 14 | // The default cache policy for this cache 15 | // Requests that store data in the cache will use this cache policy if their cache policy is set to ASIUseDefaultCachePolicy 16 | // Defaults to ASIAskServerIfModifiedWhenStaleCachePolicy 17 | ASICachePolicy defaultCachePolicy; 18 | 19 | // The directory in which cached data will be stored 20 | // Defaults to a directory called 'ASIHTTPRequestCache' in the temporary directory 21 | NSString *storagePath; 22 | 23 | // Mediates access to the cache 24 | NSRecursiveLock *accessLock; 25 | 26 | // When YES, the cache will look for cache-control / pragma: no-cache headers, and won't reuse store responses if it finds them 27 | BOOL shouldRespectCacheControlHeaders; 28 | } 29 | 30 | // Returns a static instance of an ASIDownloadCache 31 | // In most circumstances, it will make sense to use this as a global cache, rather than creating your own cache 32 | // To make ASIHTTPRequests use it automatically, use [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]]; 33 | + (id)sharedCache; 34 | 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 | + (BOOL)serverAllowsResponseCachingForRequest:(ASIHTTPRequest *)request; 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 | 42 | @property (assign, nonatomic) ASICachePolicy defaultCachePolicy; 43 | @property (retain, nonatomic) NSString *storagePath; 44 | @property (retain) NSRecursiveLock *accessLock; 45 | @property (assign) BOOL shouldRespectCacheControlHeaders; 46 | @end 47 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIDownloadCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // ASIDownloadCache.m 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 01/05/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "ASIDownloadCache.h" 10 | #import "ASIHTTPRequest.h" 11 | #import 12 | 13 | static ASIDownloadCache *sharedCache = nil; 14 | 15 | static NSString *sessionCacheFolder = @"SessionStore"; 16 | static NSString *permanentCacheFolder = @"PermanentStore"; 17 | static NSArray *fileExtensionsToHandleAsHTML = nil; 18 | 19 | @interface ASIDownloadCache () 20 | + (NSString *)keyForURL:(NSURL *)url; 21 | - (NSString *)pathToFile:(NSString *)file; 22 | @end 23 | 24 | @implementation ASIDownloadCache 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 | 35 | - (id)init 36 | { 37 | self = [super init]; 38 | [self setShouldRespectCacheControlHeaders:YES]; 39 | [self setDefaultCachePolicy:ASIUseDefaultCachePolicy]; 40 | [self setAccessLock:[[[NSRecursiveLock alloc] init] autorelease]]; 41 | return self; 42 | } 43 | 44 | + (id)sharedCache 45 | { 46 | if (!sharedCache) { 47 | @synchronized(self) { 48 | if (!sharedCache) { 49 | sharedCache = [[self alloc] init]; 50 | [sharedCache setStoragePath:[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ASIHTTPRequestCache"]]; 51 | } 52 | } 53 | } 54 | return sharedCache; 55 | } 56 | 57 | - (void)dealloc 58 | { 59 | [storagePath release]; 60 | [accessLock release]; 61 | [super dealloc]; 62 | } 63 | 64 | - (NSString *)storagePath 65 | { 66 | [[self accessLock] lock]; 67 | NSString *p = [[storagePath retain] autorelease]; 68 | [[self accessLock] unlock]; 69 | return p; 70 | } 71 | 72 | 73 | - (void)setStoragePath:(NSString *)path 74 | { 75 | [[self accessLock] lock]; 76 | [self clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy]; 77 | [storagePath release]; 78 | storagePath = [path retain]; 79 | 80 | NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; 81 | 82 | BOOL isDirectory = NO; 83 | NSArray *directories = [NSArray arrayWithObjects:path,[path stringByAppendingPathComponent:sessionCacheFolder],[path stringByAppendingPathComponent:permanentCacheFolder],nil]; 84 | for (NSString *directory in directories) { 85 | BOOL exists = [fileManager fileExistsAtPath:directory isDirectory:&isDirectory]; 86 | if (exists && !isDirectory) { 87 | [[self accessLock] unlock]; 88 | [NSException raise:@"FileExistsAtCachePath" format:@"Cannot create a directory for the cache at '%@', because a file already exists",directory]; 89 | } else if (!exists) { 90 | [fileManager createDirectoryAtPath:directory withIntermediateDirectories:NO attributes:nil error:nil]; 91 | if (![fileManager fileExistsAtPath:directory]) { 92 | [[self accessLock] unlock]; 93 | [NSException raise:@"FailedToCreateCacheDirectory" format:@"Failed to create a directory for the cache at '%@'",directory]; 94 | } 95 | } 96 | } 97 | [self clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy]; 98 | [[self accessLock] unlock]; 99 | } 100 | 101 | - (void)updateExpiryForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge 102 | { 103 | NSString *headerPath = [self pathToStoreCachedResponseHeadersForRequest:request]; 104 | NSMutableDictionary *cachedHeaders = [NSMutableDictionary dictionaryWithContentsOfFile:headerPath]; 105 | if (!cachedHeaders) { 106 | return; 107 | } 108 | NSDate *expires = [self expiryDateForRequest:request maxAge:maxAge]; 109 | if (!expires) { 110 | return; 111 | } 112 | [cachedHeaders setObject:[[NSNumber numberWithDouble:[expires timeIntervalSince1970]] description] forKey:@"X-ASIHTTPRequest-Expires"]; 113 | [cachedHeaders writeToFile:headerPath atomically:NO]; 114 | } 115 | 116 | - (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge 117 | { 118 | return [ASIHTTPRequest expiryDateForRequest:request maxAge:maxAge]; 119 | } 120 | 121 | - (void)storeResponseForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge 122 | { 123 | [[self accessLock] lock]; 124 | 125 | if ([request error] || ![request responseHeaders] || ([request cachePolicy] & ASIDoNotWriteToCacheCachePolicy)) { 126 | [[self accessLock] unlock]; 127 | return; 128 | } 129 | 130 | // We only cache 200/OK or redirect reponses (redirect responses are cached so the cache works better with no internet connection) 131 | int responseCode = [request responseStatusCode]; 132 | if (responseCode != 200 && responseCode != 301 && responseCode != 302 && responseCode != 303 && responseCode != 307) { 133 | [[self accessLock] unlock]; 134 | return; 135 | } 136 | 137 | if ([self shouldRespectCacheControlHeaders] && ![[self class] serverAllowsResponseCachingForRequest:request]) { 138 | [[self accessLock] unlock]; 139 | return; 140 | } 141 | 142 | NSString *headerPath = [self pathToStoreCachedResponseHeadersForRequest:request]; 143 | NSString *dataPath = [self pathToStoreCachedResponseDataForRequest:request]; 144 | 145 | NSMutableDictionary *responseHeaders = [NSMutableDictionary dictionaryWithDictionary:[request responseHeaders]]; 146 | if ([request isResponseCompressed]) { 147 | [responseHeaders removeObjectForKey:@"Content-Encoding"]; 148 | } 149 | 150 | // Create a special 'X-ASIHTTPRequest-Expires' header 151 | // This is what we use for deciding if cached data is current, rather than parsing the expires / max-age headers individually each time 152 | // We store this as a timestamp to make reading it easier as NSDateFormatter is quite expensive 153 | 154 | NSDate *expires = [self expiryDateForRequest:request maxAge:maxAge]; 155 | if (expires) { 156 | [responseHeaders setObject:[[NSNumber numberWithDouble:[expires timeIntervalSince1970]] description] forKey:@"X-ASIHTTPRequest-Expires"]; 157 | } 158 | 159 | // Store the response code in a custom header so we can reuse it later 160 | 161 | // We'll change 304/Not Modified to 200/OK because this is likely to be us updating the cached headers with a conditional GET 162 | int statusCode = [request responseStatusCode]; 163 | if (statusCode == 304) { 164 | statusCode = 200; 165 | } 166 | [responseHeaders setObject:[[NSNumber numberWithInt:statusCode] description] forKey:@"X-ASIHTTPRequest-Response-Status-Code"]; 167 | [request setResponseHeaders:responseHeaders]; 168 | [responseHeaders writeToFile:headerPath atomically:NO]; 169 | 170 | if ([request responseData]) { 171 | [[request responseData] writeToFile:dataPath atomically:NO]; 172 | } else if ([request downloadDestinationPath] && ![[request downloadDestinationPath] isEqualToString:dataPath]) { 173 | NSError *error = nil; 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]; 180 | } 181 | [[self accessLock] unlock]; 182 | } 183 | 184 | - (NSDictionary *)cachedResponseHeadersForURL:(NSURL *)url 185 | { 186 | NSString *path = [self pathToCachedResponseHeadersForURL:url]; 187 | if (path) { 188 | return [NSDictionary dictionaryWithContentsOfFile:path]; 189 | } 190 | return nil; 191 | } 192 | 193 | - (NSData *)cachedResponseDataForURL:(NSURL *)url 194 | { 195 | NSString *path = [self pathToCachedResponseDataForURL:url]; 196 | if (path) { 197 | return [NSData dataWithContentsOfFile:path]; 198 | } 199 | return nil; 200 | } 201 | 202 | - (NSString *)pathToCachedResponseDataForURL:(NSURL *)url 203 | { 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 205 | NSString *extension = [[url path] pathExtension]; 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]]) { 210 | extension = @"html"; 211 | } 212 | return [self pathToFile:[[[self class] keyForURL:url] stringByAppendingPathExtension:extension]]; 213 | } 214 | 215 | + (NSArray *)fileExtensionsToHandleAsHTML 216 | { 217 | return fileExtensionsToHandleAsHTML; 218 | } 219 | 220 | 221 | - (NSString *)pathToCachedResponseHeadersForURL:(NSURL *)url 222 | { 223 | return [self pathToFile:[[[self class] keyForURL:url] stringByAppendingPathExtension:@"cachedheaders"]]; 224 | } 225 | 226 | - (NSString *)pathToFile:(NSString *)file 227 | { 228 | [[self accessLock] lock]; 229 | if (![self storagePath]) { 230 | [[self accessLock] unlock]; 231 | return nil; 232 | } 233 | 234 | NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; 235 | 236 | // Look in the session store 237 | NSString *dataPath = [[[self storagePath] stringByAppendingPathComponent:sessionCacheFolder] stringByAppendingPathComponent:file]; 238 | if ([fileManager fileExistsAtPath:dataPath]) { 239 | [[self accessLock] unlock]; 240 | return dataPath; 241 | } 242 | // Look in the permanent store 243 | dataPath = [[[self storagePath] stringByAppendingPathComponent:permanentCacheFolder] stringByAppendingPathComponent:file]; 244 | if ([fileManager fileExistsAtPath:dataPath]) { 245 | [[self accessLock] unlock]; 246 | return dataPath; 247 | } 248 | [[self accessLock] unlock]; 249 | return nil; 250 | } 251 | 252 | 253 | - (NSString *)pathToStoreCachedResponseDataForRequest:(ASIHTTPRequest *)request 254 | { 255 | [[self accessLock] lock]; 256 | if (![self storagePath]) { 257 | [[self accessLock] unlock]; 258 | return nil; 259 | } 260 | 261 | NSString *path = [[self storagePath] stringByAppendingPathComponent:([request cacheStoragePolicy] == ASICacheForSessionDurationCacheStoragePolicy ? sessionCacheFolder : permanentCacheFolder)]; 262 | 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 | NSString *extension = [[[request url] path] pathExtension]; 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]]) { 269 | extension = @"html"; 270 | } 271 | path = [path stringByAppendingPathComponent:[[[self class] keyForURL:[request url]] stringByAppendingPathExtension:extension]]; 272 | [[self accessLock] unlock]; 273 | return path; 274 | } 275 | 276 | - (NSString *)pathToStoreCachedResponseHeadersForRequest:(ASIHTTPRequest *)request 277 | { 278 | [[self accessLock] lock]; 279 | if (![self storagePath]) { 280 | [[self accessLock] unlock]; 281 | return nil; 282 | } 283 | NSString *path = [[self storagePath] stringByAppendingPathComponent:([request cacheStoragePolicy] == ASICacheForSessionDurationCacheStoragePolicy ? sessionCacheFolder : permanentCacheFolder)]; 284 | path = [path stringByAppendingPathComponent:[[[self class] keyForURL:[request url]] stringByAppendingPathExtension:@"cachedheaders"]]; 285 | [[self accessLock] unlock]; 286 | return path; 287 | } 288 | 289 | - (void)removeCachedDataForURL:(NSURL *)url 290 | { 291 | [[self accessLock] lock]; 292 | if (![self storagePath]) { 293 | [[self accessLock] unlock]; 294 | return; 295 | } 296 | NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; 297 | 298 | NSString *path = [self pathToCachedResponseHeadersForURL:url]; 299 | if (path) { 300 | [fileManager removeItemAtPath:path error:NULL]; 301 | } 302 | 303 | path = [self pathToCachedResponseDataForURL:url]; 304 | if (path) { 305 | [fileManager removeItemAtPath:path error:NULL]; 306 | } 307 | [[self accessLock] unlock]; 308 | } 309 | 310 | - (void)removeCachedDataForRequest:(ASIHTTPRequest *)request 311 | { 312 | [self removeCachedDataForURL:[request url]]; 313 | } 314 | 315 | - (BOOL)isCachedDataCurrentForRequest:(ASIHTTPRequest *)request 316 | { 317 | [[self accessLock] lock]; 318 | if (![self storagePath]) { 319 | [[self accessLock] unlock]; 320 | return NO; 321 | } 322 | NSDictionary *cachedHeaders = [self cachedResponseHeadersForURL:[request url]]; 323 | if (!cachedHeaders) { 324 | [[self accessLock] unlock]; 325 | return NO; 326 | } 327 | NSString *dataPath = [self pathToCachedResponseDataForURL:[request url]]; 328 | if (!dataPath) { 329 | [[self accessLock] unlock]; 330 | return NO; 331 | } 332 | 333 | // New content is not different 334 | if ([request responseStatusCode] == 304) { 335 | [[self accessLock] unlock]; 336 | return YES; 337 | } 338 | 339 | // If we already have response headers for this request, check to see if the new content is different 340 | // We check [request complete] so that we don't end up comparing response headers from a redirection with these 341 | if ([request responseHeaders] && [request complete]) { 342 | 343 | // If the Etag or Last-Modified date are different from the one we have, we'll have to fetch this resource again 344 | NSArray *headersToCompare = [NSArray arrayWithObjects:@"Etag",@"Last-Modified",nil]; 345 | for (NSString *header in headersToCompare) { 346 | if (![[[request responseHeaders] objectForKey:header] isEqualToString:[cachedHeaders objectForKey:header]]) { 347 | [[self accessLock] unlock]; 348 | return NO; 349 | } 350 | } 351 | } 352 | 353 | if ([self shouldRespectCacheControlHeaders]) { 354 | 355 | // Look for X-ASIHTTPRequest-Expires header to see if the content is out of date 356 | NSNumber *expires = [cachedHeaders objectForKey:@"X-ASIHTTPRequest-Expires"]; 357 | if (expires) { 358 | if ([[NSDate dateWithTimeIntervalSince1970:[expires doubleValue]] timeIntervalSinceNow] >= 0) { 359 | [[self accessLock] unlock]; 360 | return YES; 361 | } 362 | } 363 | 364 | // No explicit expiration time sent by the server 365 | [[self accessLock] unlock]; 366 | return NO; 367 | } 368 | 369 | 370 | [[self accessLock] unlock]; 371 | return YES; 372 | } 373 | 374 | - (ASICachePolicy)defaultCachePolicy 375 | { 376 | [[self accessLock] lock]; 377 | ASICachePolicy cp = defaultCachePolicy; 378 | [[self accessLock] unlock]; 379 | return cp; 380 | } 381 | 382 | 383 | - (void)setDefaultCachePolicy:(ASICachePolicy)cachePolicy 384 | { 385 | [[self accessLock] lock]; 386 | if (!cachePolicy) { 387 | defaultCachePolicy = ASIAskServerIfModifiedWhenStaleCachePolicy; 388 | } else { 389 | defaultCachePolicy = cachePolicy; 390 | } 391 | [[self accessLock] unlock]; 392 | } 393 | 394 | - (void)clearCachedResponsesForStoragePolicy:(ASICacheStoragePolicy)storagePolicy 395 | { 396 | [[self accessLock] lock]; 397 | if (![self storagePath]) { 398 | [[self accessLock] unlock]; 399 | return; 400 | } 401 | NSString *path = [[self storagePath] stringByAppendingPathComponent:(storagePolicy == ASICacheForSessionDurationCacheStoragePolicy ? sessionCacheFolder : permanentCacheFolder)]; 402 | 403 | NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; 404 | 405 | BOOL isDirectory = NO; 406 | BOOL exists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory]; 407 | if (!exists || !isDirectory) { 408 | [[self accessLock] unlock]; 409 | return; 410 | } 411 | NSError *error = nil; 412 | NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:path error:&error]; 413 | if (error) { 414 | [[self accessLock] unlock]; 415 | [NSException raise:@"FailedToTraverseCacheDirectory" format:@"Listing cache directory failed at path '%@'",path]; 416 | } 417 | for (NSString *file in cacheFiles) { 418 | [fileManager removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error]; 419 | if (error) { 420 | [[self accessLock] unlock]; 421 | [NSException raise:@"FailedToRemoveCacheFile" format:@"Failed to remove cached data at path '%@'",path]; 422 | } 423 | } 424 | [[self accessLock] unlock]; 425 | } 426 | 427 | + (BOOL)serverAllowsResponseCachingForRequest:(ASIHTTPRequest *)request 428 | { 429 | NSString *cacheControl = [[[request responseHeaders] objectForKey:@"Cache-Control"] lowercaseString]; 430 | if (cacheControl) { 431 | if ([cacheControl isEqualToString:@"no-cache"] || [cacheControl isEqualToString:@"no-store"]) { 432 | return NO; 433 | } 434 | } 435 | NSString *pragma = [[[request responseHeaders] objectForKey:@"Pragma"] lowercaseString]; 436 | if (pragma) { 437 | if ([pragma isEqualToString:@"no-cache"]) { 438 | return NO; 439 | } 440 | } 441 | return YES; 442 | } 443 | 444 | + (NSString *)keyForURL:(NSURL *)url 445 | { 446 | NSString *urlString = [url absoluteString]; 447 | if ([urlString length] == 0) { 448 | return nil; 449 | } 450 | 451 | // Strip trailing slashes so http://allseeing-i.com/ASIHTTPRequest/ is cached the same as http://allseeing-i.com/ASIHTTPRequest 452 | // if ([[urlString substringFromIndex:[urlString length]-1] isEqualToString:@"/"]) { 453 | // urlString = [urlString substringToIndex:[urlString length]-1]; 454 | // } 455 | 456 | // Borrowed from: http://stackoverflow.com/questions/652300/using-md5-hash-on-a-string-in-cocoa 457 | const char *cStr = [urlString UTF8String]; 458 | unsigned char result[16]; 459 | CC_MD5(cStr, (CC_LONG)strlen(cStr), result); 460 | return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]]; 461 | } 462 | 463 | - (BOOL)canUseCachedDataForRequest:(ASIHTTPRequest *)request 464 | { 465 | // Ensure the request is allowed to read from the cache 466 | if ([request cachePolicy] & ASIDoNotReadFromCacheCachePolicy) { 467 | return NO; 468 | 469 | // If we don't want to load the request whatever happens, always pretend we have cached data even if we don't 470 | } else if ([request cachePolicy] & ASIDontLoadCachePolicy) { 471 | return YES; 472 | } 473 | 474 | NSDictionary *headers = [self cachedResponseHeadersForURL:[request url]]; 475 | if (!headers) { 476 | return NO; 477 | } 478 | NSString *dataPath = [self pathToCachedResponseDataForURL:[request url]]; 479 | if (!dataPath) { 480 | return NO; 481 | } 482 | 483 | // If we get here, we have cached data 484 | 485 | // If we have cached data, we can use it 486 | if ([request cachePolicy] & ASIOnlyLoadIfNotCachedCachePolicy) { 487 | return YES; 488 | 489 | // If we want to fallback to the cache after an error 490 | } else if ([request complete] && [request cachePolicy] & ASIFallbackToCacheIfLoadFailsCachePolicy) { 491 | return YES; 492 | 493 | // If we have cached data that is current, we can use it 494 | } else if ([request cachePolicy] & ASIAskServerIfModifiedWhenStaleCachePolicy) { 495 | if ([self isCachedDataCurrentForRequest:request]) { 496 | return YES; 497 | } 498 | 499 | // If we've got headers from a conditional GET and the cached data is still current, we can use it 500 | } else if ([request cachePolicy] & ASIAskServerIfModifiedCachePolicy) { 501 | if (![request responseHeaders]) { 502 | return NO; 503 | } else if ([self isCachedDataCurrentForRequest:request]) { 504 | return YES; 505 | } 506 | } 507 | return NO; 508 | } 509 | 510 | @synthesize storagePath; 511 | @synthesize defaultCachePolicy; 512 | @synthesize accessLock; 513 | @synthesize shouldRespectCacheControlHeaders; 514 | @end 515 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIHTTPRequestConfig.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIHTTPRequestConfig.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 14/12/2009. 6 | // Copyright 2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | 10 | // ====== 11 | // Debug output configuration options 12 | // ====== 13 | 14 | // When set to 1 ASIHTTPRequests will print information about what a request is doing 15 | #ifndef DEBUG_REQUEST_STATUS 16 | #define DEBUG_REQUEST_STATUS 0 17 | #endif 18 | 19 | // When set to 1, ASIFormDataRequests will print information about the request body to the console 20 | #ifndef DEBUG_FORM_DATA_REQUEST 21 | #define DEBUG_FORM_DATA_REQUEST 0 22 | #endif 23 | 24 | // When set to 1, ASIHTTPRequests will print information about bandwidth throttling to the console 25 | #ifndef DEBUG_THROTTLING 26 | #define DEBUG_THROTTLING 0 27 | #endif 28 | 29 | // When set to 1, ASIHTTPRequests will print information about persistent connections to the console 30 | #ifndef DEBUG_PERSISTENT_CONNECTIONS 31 | #define DEBUG_PERSISTENT_CONNECTIONS 0 32 | #endif 33 | 34 | // When set to 1, ASIHTTPRequests will print information about HTTP authentication (Basic, Digest or NTLM) to the console 35 | #ifndef DEBUG_HTTP_AUTHENTICATION 36 | #define DEBUG_HTTP_AUTHENTICATION 0 37 | #endif 38 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIHTTPRequestDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIHTTPRequestDelegate.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 13/04/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | @class ASIHTTPRequest; 10 | 11 | @protocol ASIHTTPRequestDelegate 12 | 13 | @optional 14 | 15 | // These are the default delegate methods for request status 16 | // You can use different ones by setting didStartSelector / didFinishSelector / didFailSelector 17 | - (void)requestStarted:(ASIHTTPRequest *)request; 18 | - (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders; 19 | - (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL; 20 | - (void)requestFinished:(ASIHTTPRequest *)request; 21 | - (void)requestFailed:(ASIHTTPRequest *)request; 22 | - (void)requestRedirected:(ASIHTTPRequest *)request; 23 | 24 | // When a delegate implements this method, it is expected to process all incoming data itself 25 | // This means that responseData / responseString / downloadDestinationPath etc are ignored 26 | // You can have the request call a different method by setting didReceiveDataSelector 27 | - (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data; 28 | 29 | // If a delegate implements one of these, it will be asked to supply credentials when none are available 30 | // The delegate can then either restart the request ([request retryUsingSuppliedCredentials]) once credentials have been set 31 | // or cancel it ([request cancelAuthentication]) 32 | - (void)authenticationNeededForRequest:(ASIHTTPRequest *)request; 33 | - (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request; 34 | 35 | @end 36 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIInputStream.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIInputStream.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 10/08/2009. 6 | // Copyright 2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class ASIHTTPRequest; 12 | 13 | // This is a wrapper for NSInputStream that pretends to be an NSInputStream itself 14 | // Subclassing NSInputStream seems to be tricky, and may involve overriding undocumented methods, so we'll cheat instead. 15 | // It is used by ASIHTTPRequest whenever we have a request body, and handles measuring and throttling the bandwidth used for uploading 16 | 17 | @interface ASIInputStream : NSObject { 18 | NSInputStream *stream; 19 | ASIHTTPRequest *request; 20 | } 21 | + (id)inputStreamWithFileAtPath:(NSString *)path request:(ASIHTTPRequest *)request; 22 | + (id)inputStreamWithData:(NSData *)data request:(ASIHTTPRequest *)request; 23 | 24 | @property (retain, nonatomic) NSInputStream *stream; 25 | @property (assign, nonatomic) ASIHTTPRequest *request; 26 | @end 27 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIInputStream.m: -------------------------------------------------------------------------------- 1 | // 2 | // ASIInputStream.m 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 10/08/2009. 6 | // Copyright 2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "ASIInputStream.h" 10 | #import "ASIHTTPRequest.h" 11 | 12 | // Used to ensure only one request can read data at once 13 | static NSLock *readLock = nil; 14 | 15 | @implementation ASIInputStream 16 | 17 | + (void)initialize 18 | { 19 | if (self == [ASIInputStream class]) { 20 | readLock = [[NSLock alloc] init]; 21 | } 22 | } 23 | 24 | + (id)inputStreamWithFileAtPath:(NSString *)path request:(ASIHTTPRequest *)theRequest 25 | { 26 | ASIInputStream *theStream = [[[self alloc] init] autorelease]; 27 | [theStream setRequest:theRequest]; 28 | [theStream setStream:[NSInputStream inputStreamWithFileAtPath:path]]; 29 | return theStream; 30 | } 31 | 32 | + (id)inputStreamWithData:(NSData *)data request:(ASIHTTPRequest *)theRequest 33 | { 34 | ASIInputStream *theStream = [[[self alloc] init] autorelease]; 35 | [theStream setRequest:theRequest]; 36 | [theStream setStream:[NSInputStream inputStreamWithData:data]]; 37 | return theStream; 38 | } 39 | 40 | - (void)dealloc 41 | { 42 | [stream release]; 43 | [super dealloc]; 44 | } 45 | 46 | // Called when CFNetwork wants to read more of our request body 47 | // When throttling is on, we ask ASIHTTPRequest for the maximum amount of data we can read 48 | - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len 49 | { 50 | [readLock lock]; 51 | unsigned long toRead = len; 52 | if ([ASIHTTPRequest isBandwidthThrottled]) { 53 | toRead = [ASIHTTPRequest maxUploadReadLength]; 54 | if (toRead > len) { 55 | toRead = len; 56 | } else if (toRead == 0) { 57 | toRead = 1; 58 | } 59 | [request performThrottling]; 60 | } 61 | [readLock unlock]; 62 | NSInteger rv = [stream read:buffer maxLength:toRead]; 63 | if (rv > 0) 64 | [ASIHTTPRequest incrementBandwidthUsedInLastSecond:rv]; 65 | return rv; 66 | } 67 | 68 | /* 69 | * Implement NSInputStream mandatory methods to make sure they are implemented 70 | * (necessary for MacRuby for example) and avoid the overhead of method 71 | * forwarding for these common methods. 72 | */ 73 | - (void)open 74 | { 75 | [stream open]; 76 | } 77 | 78 | - (void)close 79 | { 80 | [stream close]; 81 | } 82 | 83 | - (id)delegate 84 | { 85 | return [stream delegate]; 86 | } 87 | 88 | - (void)setDelegate:(id)delegate 89 | { 90 | [stream setDelegate:delegate]; 91 | } 92 | 93 | - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode 94 | { 95 | [stream scheduleInRunLoop:aRunLoop forMode:mode]; 96 | } 97 | 98 | - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode 99 | { 100 | [stream removeFromRunLoop:aRunLoop forMode:mode]; 101 | } 102 | 103 | - (id)propertyForKey:(NSString *)key 104 | { 105 | return [stream propertyForKey:key]; 106 | } 107 | 108 | - (BOOL)setProperty:(id)property forKey:(NSString *)key 109 | { 110 | return [stream setProperty:property forKey:key]; 111 | } 112 | 113 | - (NSStreamStatus)streamStatus 114 | { 115 | return [stream streamStatus]; 116 | } 117 | 118 | - (NSError *)streamError 119 | { 120 | return [stream streamError]; 121 | } 122 | 123 | // If we get asked to perform a method we don't have (probably internal ones), 124 | // we'll just forward the message to our stream 125 | 126 | - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector 127 | { 128 | return [stream methodSignatureForSelector:aSelector]; 129 | } 130 | 131 | - (void)forwardInvocation:(NSInvocation *)anInvocation 132 | { 133 | [anInvocation invokeWithTarget:stream]; 134 | } 135 | 136 | @synthesize stream; 137 | @synthesize request; 138 | @end 139 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/ASIProgressDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIProgressDelegate.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 13/04/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | @class ASIHTTPRequest; 10 | 11 | @protocol ASIProgressDelegate 12 | 13 | @optional 14 | 15 | // These methods are used to update UIProgressViews (iPhone OS) or NSProgressIndicators (Mac OS X) 16 | // If you are using a custom progress delegate, you may find it easier to implement didReceiveBytes / didSendBytes instead 17 | #if TARGET_OS_IPHONE 18 | - (void)setProgress:(float)newProgress; 19 | #else 20 | - (void)setDoubleValue:(double)newProgress; 21 | - (void)setMaxValue:(double)newMax; 22 | #endif 23 | 24 | // Called when the request receives some data - bytes is the length of that data 25 | - (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes; 26 | 27 | // Called when the request sends some data 28 | // The first 32KB (128KB on older platforms) of data sent is not included in this amount because of limitations with the CFNetwork API 29 | // bytes may be less than zero if a request needs to remove upload progress (probably because the request needs to run again) 30 | - (void)request:(ASIHTTPRequest *)request didSendBytes:(long long)bytes; 31 | 32 | // Called when a request needs to change the length of the content to download 33 | - (void)request:(ASIHTTPRequest *)request incrementDownloadSizeBy:(long long)newLength; 34 | 35 | // Called when a request needs to change the length of the content to upload 36 | // newLength may be less than zero when a request needs to remove the size of the internal buffer from progress tracking 37 | - (void)request:(ASIHTTPRequest *)request incrementUploadSizeBy:(long long)newLength; 38 | @end 39 | -------------------------------------------------------------------------------- /SimpleBrowser/ASIHTTPRequest/Reachability/Reachability.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | File: Reachability.h 4 | Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs. 5 | 6 | Version: 2.0.4ddg 7 | */ 8 | 9 | /* 10 | Significant additions made by Andrew W. Donoho, August 11, 2009. 11 | This is a derived work of Apple's Reachability v2.0 class. 12 | 13 | The below license is the new BSD license with the OSI recommended personalizations. 14 | 15 | 16 | Extensions Copyright (C) 2009 Donoho Design Group, LLC. All Rights Reserved. 17 | 18 | Redistribution and use in source and binary forms, with or without 19 | modification, are permitted provided that the following conditions are 20 | met: 21 | 22 | * Redistributions of source code must retain the above copyright notice, 23 | this list of conditions and the following disclaimer. 24 | 25 | * Redistributions in binary form must reproduce the above copyright 26 | notice, this list of conditions and the following disclaimer in the 27 | documentation and/or other materials provided with the distribution. 28 | 29 | * Neither the name of Andrew W. Donoho nor Donoho Design Group, L.L.C. 30 | may be used to endorse or promote products derived from this software 31 | without specific prior written permission. 32 | 33 | THIS SOFTWARE IS PROVIDED BY DONOHO DESIGN GROUP, L.L.C. "AS IS" AND ANY 34 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 35 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 36 | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 37 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 38 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 39 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 40 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 41 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 42 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 43 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 44 | 45 | */ 46 | 47 | 48 | /* 49 | 50 | Apple's Original License on Reachability v2.0 51 | 52 | Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. 53 | ("Apple") in consideration of your agreement to the following terms, and your 54 | use, installation, modification or redistribution of this Apple software 55 | constitutes acceptance of these terms. If you do not agree with these terms, 56 | please do not use, install, modify or redistribute this Apple software. 57 | 58 | In consideration of your agreement to abide by the following terms, and subject 59 | to these terms, Apple grants you a personal, non-exclusive license, under 60 | Apple's copyrights in this original Apple software (the "Apple Software"), to 61 | use, reproduce, modify and redistribute the Apple Software, with or without 62 | modifications, in source and/or binary forms; provided that if you redistribute 63 | the Apple Software in its entirety and without modifications, you must retain 64 | this notice and the following text and disclaimers in all such redistributions 65 | of the Apple Software. 66 | 67 | Neither the name, trademarks, service marks or logos of Apple Inc. may be used 68 | to endorse or promote products derived from the Apple Software without specific 69 | prior written permission from Apple. Except as expressly stated in this notice, 70 | no other rights or licenses, express or implied, are granted by Apple herein, 71 | including but not limited to any patent rights that may be infringed by your 72 | derivative works or by other works in which the Apple Software may be 73 | incorporated. 74 | 75 | The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO 76 | WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED 77 | WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR 78 | PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN 79 | COMBINATION WITH YOUR PRODUCTS. 80 | 81 | IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR 82 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 83 | GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 84 | ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR 85 | DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF 86 | CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF 87 | APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 88 | 89 | Copyright (C) 2009 Apple Inc. All Rights Reserved. 90 | 91 | */ 92 | 93 | 94 | /* 95 | DDG extensions include: 96 | Each reachability object now has a copy of the key used to store it in a 97 | dictionary. This allows each observer to quickly determine if the event is 98 | important to them. 99 | 100 | -currentReachabilityStatus also has a significantly different decision criteria than 101 | Apple's code. 102 | 103 | A multiple convenience test methods have been added. 104 | */ 105 | 106 | #import 107 | #import 108 | #import 109 | 110 | #define USE_DDG_EXTENSIONS 1 // Use DDG's Extensions to test network criteria. 111 | // Since NSAssert and NSCAssert are used in this code, 112 | // I recommend you set NS_BLOCK_ASSERTIONS=1 in the release versions of your projects. 113 | 114 | enum { 115 | 116 | // DDG NetworkStatus Constant Names. 117 | kNotReachable = 0, // Apple's code depends upon 'NotReachable' being the same value as 'NO'. 118 | kReachableViaWWAN, // Switched order from Apple's enum. WWAN is active before WiFi. 119 | kReachableViaWiFi 120 | 121 | }; 122 | typedef uint32_t NetworkStatus; 123 | 124 | enum { 125 | 126 | // Apple NetworkStatus Constant Names. 127 | NotReachable = kNotReachable, 128 | ReachableViaWiFi = kReachableViaWiFi, 129 | ReachableViaWWAN = kReachableViaWWAN 130 | 131 | }; 132 | 133 | 134 | extern NSString *const kInternetConnection; 135 | extern NSString *const kLocalWiFiConnection; 136 | extern NSString *const kReachabilityChangedNotification; 137 | 138 | @interface Reachability: NSObject { 139 | 140 | @private 141 | NSString *key_; 142 | SCNetworkReachabilityRef reachabilityRef; 143 | 144 | } 145 | 146 | @property (copy) NSString *key; // Atomic because network operations are asynchronous. 147 | 148 | // Designated Initializer. 149 | - (Reachability *) initWithReachabilityRef: (SCNetworkReachabilityRef) ref; 150 | 151 | // Use to check the reachability of a particular host name. 152 | + (Reachability *) reachabilityWithHostName: (NSString*) hostName; 153 | 154 | // Use to check the reachability of a particular IP address. 155 | + (Reachability *) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress; 156 | 157 | // Use to check whether the default route is available. 158 | // Should be used to, at minimum, establish network connectivity. 159 | + (Reachability *) reachabilityForInternetConnection; 160 | 161 | // Use to check whether a local wifi connection is available. 162 | + (Reachability *) reachabilityForLocalWiFi; 163 | 164 | //Start listening for reachability notifications on the current run loop. 165 | - (BOOL) startNotifier; 166 | - (void) stopNotifier; 167 | 168 | // Comparison routines to enable choosing actions in a notification. 169 | - (BOOL) isEqual: (Reachability *) r; 170 | 171 | // These are the status tests. 172 | - (NetworkStatus) currentReachabilityStatus; 173 | 174 | // The main direct test of reachability. 175 | - (BOOL) isReachable; 176 | 177 | // WWAN may be available, but not active until a connection has been established. 178 | // WiFi may require a connection for VPN on Demand. 179 | - (BOOL) isConnectionRequired; // Identical DDG variant. 180 | - (BOOL) connectionRequired; // Apple's routine. 181 | 182 | // Dynamic, on demand connection? 183 | - (BOOL) isConnectionOnDemand; 184 | 185 | // Is user intervention required? 186 | - (BOOL) isInterventionRequired; 187 | 188 | // Routines for specific connection testing by your app. 189 | - (BOOL) isReachableViaWWAN; 190 | - (BOOL) isReachableViaWiFi; 191 | 192 | - (SCNetworkReachabilityFlags) reachabilityFlags; 193 | 194 | @end 195 | -------------------------------------------------------------------------------- /SimpleBrowser/CSSParser.h: -------------------------------------------------------------------------------- 1 | // 2 | // CSSParser.h 3 | // TextTransfer 4 | // 5 | // Created by Ben Copsey on 29/08/2011. 6 | // Copyright 2011 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | // 10 | // This parser replaces urls in the content of a stylesheet or other set of CSS declarations 11 | // (eg style tags or style attributes) 12 | // 13 | 14 | #import 15 | #import "ContentParser.h" 16 | 17 | @interface CSSParser : ContentParser 18 | 19 | + (NSString *)replaceURLsInCSSString:(NSString *)string withBaseURL:(NSURL *)baseURL; 20 | 21 | 22 | @end 23 | -------------------------------------------------------------------------------- /SimpleBrowser/CSSParser.m: -------------------------------------------------------------------------------- 1 | // 2 | // CSSParser.m 3 | // TextTransfer 4 | // 5 | // Created by Ben Copsey on 29/08/2011. 6 | // Copyright 2011 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "CSSParser.h" 10 | #import "ASIHTTPRequest.h" 11 | 12 | @implementation CSSParser 13 | 14 | + (BOOL)parseDataForRequest:(ASIHTTPRequest *)request error:(NSError **)error 15 | { 16 | NSURL *baseURL = [request url]; 17 | if ([request downloadDestinationPath]) { 18 | NSError *err = nil; 19 | NSString *css = [NSString stringWithContentsOfFile:[request downloadDestinationPath] encoding:[request responseEncoding] error:&err]; 20 | if (!err) { 21 | [[self replaceURLsInCSSString:css withBaseURL:baseURL] writeToFile:[request downloadDestinationPath] atomically:NO encoding:[request responseEncoding] error:&err]; 22 | } 23 | if (err) { 24 | if (error) { 25 | *error = [NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to write response CSS",NSLocalizedDescriptionKey,nil]]; 26 | } 27 | return FALSE; 28 | } 29 | } else { 30 | [request setRawResponseData:(NSMutableData *)[[self replaceURLsInCSSString:[request responseString] withBaseURL:baseURL] dataUsingEncoding:[request responseEncoding]]]; 31 | } 32 | [super parseDataForRequest:request error:error]; 33 | return TRUE; 34 | } 35 | 36 | // A quick and dirty way to build a list of external resource urls from a css string 37 | + (NSString *)replaceURLsInCSSString:(NSString *)string withBaseURL:(NSURL *)baseURL 38 | { 39 | NSMutableArray *urls = [NSMutableArray array]; 40 | NSScanner *scanner = [NSScanner scannerWithString:string]; 41 | [scanner setCaseSensitive:NO]; 42 | 43 | // Find urls in the the CSS string 44 | while (1) { 45 | NSString *theURL = nil; 46 | [scanner scanUpToString:@"url(" intoString:NULL]; 47 | [scanner scanString:@"url(" intoString:NULL]; 48 | [scanner scanUpToString:@")" intoString:&theURL]; 49 | if (!theURL) { 50 | break; 51 | } 52 | NSUInteger originalLength = [theURL length]; 53 | 54 | // Remove any quotes or whitespace around the url 55 | theURL = [theURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 56 | theURL = [theURL stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\"'"]]; 57 | theURL = [theURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 58 | [urls addObject:[NSDictionary dictionaryWithObjectsAndKeys:theURL,@"url",[NSNumber numberWithInt:[scanner scanLocation]-originalLength], @"location",[NSNumber numberWithInt:originalLength],@"length", nil]]; 59 | } 60 | NSMutableString *parsedResponse = [[string mutableCopy] autorelease]; 61 | int lengthToAdd = 0; 62 | 63 | // Replace urls in the CSS string, taking account of replacements we have already made and adjusting the replacement range accordingly 64 | for (NSDictionary *url in urls) { 65 | 66 | NSString *newURL = [self localURLForURL:[url objectForKey:@"url"] withBaseURL:baseURL]; 67 | 68 | [parsedResponse replaceCharactersInRange:NSMakeRange([[url objectForKey:@"location"] intValue]+lengthToAdd, [[url objectForKey:@"length"] intValue]) withString:newURL]; 69 | lengthToAdd += ([newURL length]-[[url objectForKey:@"length"] intValue]); 70 | 71 | } 72 | return parsedResponse; 73 | } 74 | 75 | 76 | @end 77 | -------------------------------------------------------------------------------- /SimpleBrowser/ContentParser.h: -------------------------------------------------------------------------------- 1 | // 2 | // ContentParser.h 3 | // TextTransfer 4 | // 5 | // Created by Ben Copsey on 29/08/2011. 6 | // Copyright 2011 All-Seeing Interactive. All rights reserved. 7 | 8 | // 9 | // The base class for parsers that modify content 10 | // 11 | 12 | #import 13 | 14 | @class ASIHTTPRequest; 15 | 16 | @interface ContentParser : NSObject 17 | 18 | + (BOOL)parseDataForRequest:(ASIHTTPRequest *)request error:(NSError **)error; 19 | + (NSString *)localURLForURL:(NSString *)url withBaseURL:(NSURL *)baseURL; 20 | 21 | @end 22 | -------------------------------------------------------------------------------- /SimpleBrowser/ContentParser.m: -------------------------------------------------------------------------------- 1 | // 2 | // ContentParser.m 3 | // TextTransfer 4 | // 5 | // Created by Ben Copsey on 29/08/2011. 6 | // Copyright 2011 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "ContentParser.h" 10 | #import "ASIHTTPRequest.h" 11 | 12 | @implementation ContentParser 13 | 14 | + (NSString *)localURLForURL:(NSString *)url withBaseURL:(NSURL *)baseURL 15 | { 16 | NSURL *theURL = [NSURL URLWithString:url relativeToURL:baseURL]; 17 | NSString *scheme = [[theURL scheme] lowercaseString]; 18 | if (scheme && ![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) { 19 | return url; 20 | } 21 | url = [theURL absoluteString]; 22 | url = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)url,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8); 23 | NSString *newURL = [NSString stringWithFormat:@"http://127.0.0.1:8080?url=%@",url]; 24 | return newURL; 25 | } 26 | 27 | + (BOOL)parseDataForRequest:(ASIHTTPRequest *)request error:(NSError **)error 28 | { 29 | NSUInteger contentLength = 0; 30 | NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease]; 31 | if ([request downloadDestinationPath]) { 32 | contentLength = [[fileManager attributesOfItemAtPath:[request downloadDestinationPath] error:NULL] fileSize]; 33 | } else { 34 | contentLength = [[request rawResponseData] length]; 35 | } 36 | // If the data was originally deflated, by now we have already inflated it, so we remove the content-encoding header 37 | NSMutableDictionary *headers = [[[request responseHeaders] mutableCopy] autorelease]; 38 | if ([request isResponseCompressed]) { 39 | [headers removeObjectForKey:@"Content-Encoding"]; 40 | } 41 | // Adds a content length header if one wasn't already included 42 | if (contentLength > 0) { 43 | [headers setValue:[NSString stringWithFormat:@"%lu",contentLength] forKey:@"Content-Length"]; 44 | } 45 | [request setResponseHeaders:headers]; 46 | return TRUE; 47 | } 48 | 49 | @end 50 | -------------------------------------------------------------------------------- /SimpleBrowser/HTMLParser.h: -------------------------------------------------------------------------------- 1 | // 2 | // HTMLParser.h 3 | // TextTransfer 4 | // 5 | // Created by Ben Copsey on 29/08/2011. 6 | // Copyright 2011 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | // 10 | // This parser replaces urls in HTML source 11 | // It uses the xpath query (xpathExpr) to find attributes containing remote urls 12 | // 13 | 14 | #import 15 | #import "ContentParser.h" 16 | 17 | @class ASIHTTPRequest; 18 | 19 | @interface HTMLParser : ContentParser; 20 | 21 | + (const char *)encodingNameForStringEncoding:(NSStringEncoding)encoding; 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /SimpleBrowser/HTMLParser.m: -------------------------------------------------------------------------------- 1 | // 2 | // HTMLParser.m 3 | // TextTransfer 4 | // 5 | // Created by Ben Copsey on 29/08/2011. 6 | // Copyright 2011 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "HTMLParser.h" 10 | #import "ASIHTTPRequest.h" 11 | #import "CSSParser.h" 12 | #import 13 | #import 14 | #import 15 | #import 16 | 17 | // I have disabled fetching audio and video content for this example 18 | //static xmlChar *xpathExpr = (xmlChar *)"//head|//link/@href|//a/@href|//script/@src|//img/@src|//frame/@src|//iframe/@src|//style|//*/@style|//source/@src|//video/@poster|//audio/@src"; 19 | 20 | static xmlChar *xpathExpr = (xmlChar *)"//head|//link/@href|//a/@href|//script/@src|//img/@src|//frame/@src|//iframe/@src|//style|//*/@style"; 21 | 22 | @implementation HTMLParser 23 | 24 | + (BOOL)parseDataForRequest:(ASIHTTPRequest *)request error:(NSError **)error 25 | { 26 | NSStringEncoding encoding = [request responseEncoding]; 27 | NSString *string = [[NSString alloc] initWithContentsOfFile:[request downloadDestinationPath] usedEncoding:&encoding error:NULL]; 28 | [string release]; 29 | NSURL *baseURL = [request url]; 30 | 31 | xmlInitParser(); 32 | xmlDocPtr doc; 33 | if ([request downloadDestinationPath]) { 34 | doc = htmlReadFile([[request downloadDestinationPath] cStringUsingEncoding:NSUTF8StringEncoding], [self encodingNameForStringEncoding:encoding], HTML_PARSE_RECOVER | HTML_PARSE_NONET | HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR); 35 | } else { 36 | NSData *data = [request responseData]; 37 | doc = htmlReadMemory([data bytes], (int)[data length], "", [self encodingNameForStringEncoding:encoding], HTML_PARSE_RECOVER | HTML_PARSE_NONET | HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR); 38 | } 39 | if (doc == NULL) { 40 | [super parseDataForRequest:request error:error]; 41 | return YES; 42 | } 43 | 44 | // Create xpath evaluation context 45 | xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); 46 | if(xpathCtx == NULL) { 47 | if (error) { 48 | *error = [NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to create new XPath context",NSLocalizedDescriptionKey,nil]]; 49 | } 50 | return NO; 51 | } 52 | 53 | // Evaluate xpath expression 54 | xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx); 55 | if(xpathObj == NULL) { 56 | xmlXPathFreeContext(xpathCtx); 57 | if (error) { 58 | *error = [NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to evaluate XPath expression!",NSLocalizedDescriptionKey,nil]]; 59 | } 60 | return NO; 61 | } 62 | 63 | // Now loop through our matches 64 | xmlNodeSetPtr nodes = xpathObj->nodesetval; 65 | 66 | int size = (nodes) ? nodes->nodeNr : 0; 67 | int i; 68 | for(i = size - 1; i >= 0; i--) { 69 | assert(nodes->nodeTab[i]); 70 | NSString *parentName = [NSString stringWithCString:(char *)nodes->nodeTab[i]->parent->name encoding:encoding]; 71 | NSString *nodeName = [NSString stringWithCString:(char *)nodes->nodeTab[i]->name encoding:encoding]; 72 | 73 | xmlChar *nodeValue = xmlNodeGetContent(nodes->nodeTab[i]); 74 | NSString *value = [NSString stringWithCString:(char *)nodeValue encoding:encoding]; 75 | xmlFree(nodeValue); 76 | 77 | // Here we add a element to the header to make the end result play better with javascript 78 | // (UIWebView seemed to ignore the Content-Base http header when I tried) 79 | if ([[nodeName lowercaseString] isEqualToString:@"head"]) { 80 | 81 | xmlNodePtr node = xmlNewNode(NULL, (xmlChar *)"base"); 82 | 83 | xmlNewProp(node, (xmlChar *)"href", (xmlChar *)[[baseURL absoluteString] cStringUsingEncoding:encoding]); 84 | 85 | node = xmlDocCopyNode(node, doc, 1); 86 | xmlAddChild(nodes->nodeTab[i], node); 87 | 88 | // Our xpath query matched all elements, but we're only interested in stylesheets 89 | // We do the work here rather than in the xPath query because the query is case-sensitive, and we want to match on 'stylesheet', 'StyleSHEEt' etc 90 | } else if ([[parentName lowercaseString] isEqualToString:@"link"]) { 91 | xmlChar *relAttribute = xmlGetNoNsProp(nodes->nodeTab[i]->parent,(xmlChar *)"rel"); 92 | if (relAttribute) { 93 | NSString *rel = [NSString stringWithCString:(char *)relAttribute encoding:encoding]; 94 | xmlFree(relAttribute); 95 | if ([[rel lowercaseString] isEqualToString:@"stylesheet"] || [[rel lowercaseString] isEqualToString:@"alternate stylesheet"]) { 96 | xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[[self localURLForURL:value withBaseURL:baseURL] cStringUsingEncoding:encoding]); 97 | 98 | } 99 | } 100 | 101 | // Parse the content of