/*
SRHTTPURLProtocol.m

Author: Makoto Kinoshita

Copyright 2004 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

/*
SRHTTPURLProtocol class referees CURLHandle class at http://curlhandle.sourceforge.net/ by Dan Wood.
I appreciate to his great works.
 */

#include <SystemConfiguration/SystemConfiguration.h>

#import "SRHTTPURLProtocol.h"
#import "FoundationEx.h"

@interface NSDictionary (HTTPHeader)
- (NSString*)HTTPPropertyForKey:(NSString*)key;
@end

@implementation NSDictionary (HTTPHeader)

- (NSString*)HTTPPropertyForKey:(NSString*)key
{
    NSString*   value;
    value = [self objectForKey:key];
    if (!value) {
        key = [key lowercaseString];
        value = [self objectForKey:key];
    }
    return value;
}

@end

#pragma mark -

//--------------------------------------------------------------//
#pragma mark -- SRHTTPURLProtocol callbacks --
//--------------------------------------------------------------//

// Constants
enum {
    _SRHTTPURLHeadDone = 0, 
    _SRHTTPURLReceivedBody, 
    _SRHTTPURLFinished, 
    _SRHTTPURLHappendError, 
};

// System configuration
SCDynamicStoreRef _SRGetSCDynamicStoreRef()
{
    static SCDynamicStoreRef    _storeRef = NULL;
    if (!_storeRef) {
        _storeRef = SCDynamicStoreCreate(NULL, (CFStringRef)@"xxxx", NULL, NULL);
    }
    return _storeRef;
}

// Callback functions
size_t receivedHeadData(void* buffer, size_t size, size_t numberOfItems, void* param)
{
	return [(SRHTTPURLProtocol*)param receivedHeadData:buffer size:size numberOfItems:numberOfItems];
}

size_t receivedBodyData(void* buffer, size_t size, size_t numberOfItems, void* param)
{
	return [(SRHTTPURLProtocol*)param receivedBodyData:buffer size:size numberOfItems:numberOfItems];
}

#pragma mark -

@implementation SRHTTPURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest*)request
{
    return [[[request URL] scheme] isEqualToString:@"http"];
}

+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request
{
    return request;
}

- (void)_notifyWithCachedResponse
{
    id  client;
    client = [self client];
    
    // Notify response reception
    if ([client respondsToSelector:@selector(URLProtocol:didReceiveResponse:cacheStoragePolicy:)]) {
        [client URLProtocol:self 
                didReceiveResponse:[_cachedResponse response] 
                cacheStoragePolicy:NSURLCacheStorageAllowed];
    }
    // Notify body reception
    if ([client respondsToSelector:@selector(URLProtocol:didLoadData:)]) {
        [[self client] URLProtocol:self didLoadData:[_cachedResponse data]];
    }
    // Notify completion
    if ([client respondsToSelector:@selector(URLProtocolDidFinishLoading:)]) {
        [client URLProtocolDidFinishLoading:self];
    }
}

- (id)initWithRequest:(NSURLRequest*)request 
        cachedResponse:(NSCachedURLResponse*)cachedResponse 
        client:(id <NSURLProtocolClient>)client
{
    self = [super initWithRequest:request cachedResponse:cachedResponse client:client];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _initialRequest = request;
    _request = request;
    _response = nil;
    _headers = [[NSMutableDictionary dictionary] retain];
    _data = [[NSMutableData dataWithCapacity:2048] retain];
    _cachedResponse = cachedResponse;
    
    // Use cached response if there is
    if (_cachedResponse) {
        NSDictionary*   cachedHeaders;
        cachedHeaders = [(NSHTTPURLResponse*)[_cachedResponse response] allHeaderFields];
        
        // Get header fields
        NSString*   expires;
        expires = [cachedHeaders objectForKey:@"Expires"];
        
        // When it has Expires header
        if (expires) {
            // Check expire date
            NSDate* expireDate;
            expireDate = [NSDate dateWithString:expires];
            
            // Response is not expired yet
            if ([[NSDate date] laterDate:expireDate] == expireDate) {
                // Notify cached resposne
                [self _notifyWithCachedResponse];
            }
        }
    }
    
    // Prepare for background working
    _port = [[NSPort port] retain];
    [_port setDelegate:self];
    [[NSRunLoop currentRunLoop] addPort:_port forMode:(NSString*)kCFRunLoopCommonModes];
    
    // Create CURL
    _CURL = curl_easy_init();
    if (!_CURL) {
        return nil;
    }
    
    return self;
}

- (void)dealloc
{
    if (_request != _initialRequest) {
        [_request release];
    }
    [_response release];
    [_headers release];
    [_port setDelegate:nil];
    [[NSRunLoop currentRunLoop] removePort:_port forMode:(NSString*)kCFRunLoopCommonModes];
    [_port release];
    curl_easy_cleanup(_CURL);
    [super dealloc];
}

- (void)_sendMessageWithMsgid:(unsigned)msgid components:(NSArray*)components
{
    // Send message
    NSPortMessage*  message;
    message = [[NSPortMessage alloc] initWithSendPort:_port receivePort:_port components:components];
    [message setMsgid:msgid];
    [message sendBeforeDate:[NSDate dateWithTimeIntervalSinceNow:60.0]];
    [message release];
}

//--------------------------------------------------------------//
#pragma mark -- NSURLProtocol overridden methods --
//--------------------------------------------------------------//

- (NSURLRequest*)request
{
    return _request;
}

- (NSCachedURLResponse*)cachedResponse
{
    if (_cachedResponse) {
        return _cachedResponse;
    }
    
    // Check Cache-Control header
    NSString*   cacheControl;
    cacheControl = [[_response allHeaderFields] objectForKey:@"Cache-Control"];
    if (cacheControl) {
        if ([cacheControl rangeOfString:@"no-cache"].location != NSNotFound || 
            [cacheControl rangeOfString:@"no-store"].location != NSNotFound)
        {
            // Do not cache
            return nil;
        }
    }
    
    // Create cache
    NSCachedURLResponse*    cache;
    cache = [[NSCachedURLResponse alloc] initWithResponse:_response data:_data];
    [cache autorelease];
    
    return cache;
}

- (void)startLoading
{
    [NSThread detachNewThreadSelector:@selector(_startLoading) toTarget:self withObject:nil];
}

- (void)_startLoading
{
    NSAutoreleasePool*  pool;
    pool = [[NSAutoreleasePool alloc] init];
    
    // Adjust priority
    [NSThread setThreadPriority:[NSThread threadPriority] + 0.1];
    
    int result;
    
    // Set HTTP request header
    struct curl_slist*  curlHeaders = nil;
    NSDictionary*       header;
    NSEnumerator*       enumerator;
    NSString*           key;
    header = [[self request] allHTTPHeaderFields];
    enumerator = [header keyEnumerator];
    while (key = [enumerator nextObject]) {
        NSString*   value;
        value = [header objectForKey:key];
        if (!value) {
            continue;
        }
        
        // Set header
        NSString*   pair;
        pair = [NSString stringWithFormat:@"%@: %@", key, value];
        curlHeaders = curl_slist_append(curlHeaders, [pair cString]);
        
    }
    
    // For Last-Modified header
    NSString*   lastModified;
    lastModified = [[(NSHTTPURLResponse*)[_cachedResponse response] allHeaderFields] 
            objectForKey:@"Last-Modified"];
    if (lastModified) {
        // Set If-Modified-Since header
        NSString*   pair;
        pair = [NSString stringWithFormat:@"If-Modified-Since: %@", lastModified];
        curlHeaders = curl_slist_append(curlHeaders, [pair cString]);
    }
    
    // Set headers
    result = curl_easy_setopt(_CURL, CURLOPT_HTTPHEADER, curlHeaders);
    
    // Get cookies for URL
    NSArray*        cookies;
    NSDictionary*   cookieHeader;
    cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[_request URL]];
    cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    
#if 1
    // Set cookies
    NSMutableString*    cookieString;
    cookieString = [NSMutableString string];
    enumerator = [cookieHeader keyEnumerator];
    while (key = [enumerator nextObject]) {
        NSString*   value;
        value = [cookieHeader objectForKey:key];
        if (!value) {
            continue;
        }
        
        // Add cookie to string
        [cookieString appendFormat:@"%@=%@;", key, value];
    }
    if ([cookieString length] > 0) {
        result = curl_easy_setopt(_CURL, CURLOPT_COOKIE, [cookieString cString]);
    }
#else
    // Set cookie header field
    enumerator = [cookieHeader keyEnumerator];
    while (key = [enumerator nextObject]) {
        NSString*   value;
        value = [cookieHeader objectForKey:key];
        
        if (key && value) {
            // Set header
            NSString*   pair;
            pair = [NSString stringWithFormat:@"%@: %@", key, value];
            curlHeaders = curl_slist_append(curlHeaders, [pair cString]);
        }
    }
    result = curl_easy_setopt(_CURL, CURLOPT_HTTPHEADER, curlHeaders);
#endif
    
    // Set proxy info
    NSDictionary*   proxyInfo;
    proxyInfo = (NSDictionary*)SCDynamicStoreCopyProxies(_SRGetSCDynamicStoreRef());
    if (proxyInfo) {
        NSString*   proxyHost;
        NSNumber*   proxyPort;
        proxyHost = [proxyInfo objectForKey:(NSString*)(kSCPropNetProxiesHTTPProxy)];
        proxyPort = [proxyInfo objectForKey:(NSString*)(kSCPropNetProxiesHTTPPort)];
        
        if (proxyHost && proxyPort) {
            result = curl_easy_setopt(_CURL, CURLOPT_PROXY, [proxyHost cString]);
            result = curl_easy_setopt(_CURL, CURLOPT_PROXYPORT, [proxyPort longValue]);
        }
    }
    
    // Set HTTP body for POST
    NSData* bodyData;
    bodyData = [_request HTTPBody];
    if (bodyData && [bodyData length] > 0) {
        result = curl_easy_setopt(_CURL, CURLOPT_POST, 1);
        result = curl_easy_setopt(_CURL, CURLOPT_POSTFIELDS, [bodyData bytes]);
        result = curl_easy_setopt(_CURL, CURLOPT_POSTFIELDSIZE, [bodyData length]);
    }
    
    // Setup CURL callbacks
    result = curl_easy_setopt(_CURL, CURLOPT_HEADERFUNCTION, receivedHeadData);
    result = curl_easy_setopt(_CURL, CURLOPT_WRITEHEADER, self);
    result = curl_easy_setopt(_CURL, CURLOPT_WRITEFUNCTION, receivedBodyData);
    result = curl_easy_setopt(_CURL, CURLOPT_FILE, self);
    
    // Set the URL
    result = curl_easy_setopt(_CURL, CURLOPT_URL, [[[[self request] URL] absoluteString] cString]);
    
    // Do the transfer
    result = curl_easy_perform(_CURL);
    
    // Send finished message
    [self _sendMessageWithMsgid:_SRHTTPURLFinished components:nil];
    
    [pool release];
}

- (void)stopLoading
{
}

//--------------------------------------------------------------//
#pragma mark -- Data reception --
//--------------------------------------------------------------//

- (size_t)receivedHeadData:(void*)buffer 
        size:(size_t)size 
        numberOfItems:(size_t)numberOfItems
{
    // Calc writeen size
    size_t  writtenSize;
    writtenSize = size * numberOfItems;
    
    // Create NSString
    NSString*   string;
    string = [NSString stringWithCString:buffer length:writtenSize];
    if (!string) {
        return writtenSize;
    }
    
    // Remove new line
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet newLineCharacterSet]];
    
    // Parse header
    if ([string length] > 0) {
        NSRange delimiter;
        delimiter = [string rangeOfString:@": "];
        if (delimiter.location != NSNotFound) {
            // Get HAED key and value
            NSString*   key;
            NSString*   value;
            int         location;
            key = [string substringWithRange:NSMakeRange(0, delimiter.location)];
            location = delimiter.location + delimiter.length;
            value = [string substringWithRange:NSMakeRange(location, [string length] - location)];
            
            if (key && value) {
                // Add key and value
                [_headers setObject:value forKey:key];
            }
        }
    }
    
    // Notify the end of header
    else {
        // Send HEAD message
        [self _sendMessageWithMsgid:_SRHTTPURLHeadDone components:nil];
    }
    
	return writtenSize;
}

- (size_t)receivedBodyData:(void*)buffer 
        size:(size_t)size 
        numberOfItems:(size_t)numberOfItems
{
    // Calc written size
    size_t  writtenSize;
    writtenSize = size * numberOfItems;
    
    // Create NSData
	NSData* data;
    data = [NSData dataWithBytes:buffer length:writtenSize];
    
    // Send recieved body message
    NSArray*    components = nil;
    if (data) {
        components = [NSArray arrayWithObject:data];
    }
    [self _sendMessageWithMsgid:_SRHTTPURLReceivedBody components:components];
    
    return writtenSize;
}

//--------------------------------------------------------------//
#pragma mark -- NSPort delegate --
//--------------------------------------------------------------//

- (NSString*)_firstElementOfValue:(NSString*)value others:(NSDictionary**)dict
{
    // Create character set
    NSCharacterSet* chSet;
    chSet = [NSCharacterSet characterSetWithCharactersInString:@"; "];
    
    // Create scanner
    NSScanner*  scanner;
    scanner = [NSScanner scannerWithString:value];
    
    // Scan it
    NSMutableDictionary*    others = nil;
    NSString*               scannedString;
    NSString*               firstOne = nil;
    while (![scanner isAtEnd]) {
        if ([scanner scanUpToCharactersFromSet:chSet intoString:&scannedString]) {
            // Parse it
            NSRange range;
            range = [scannedString rangeOfString:@"="];
            if (range.location != NSNotFound) {
                NSString*   key;
                NSString*   value;
                int         location;
                key = [scannedString substringWithRange:NSMakeRange(0, range.location)];
                location = range.location + range.length;
                value = [scannedString substringWithRange:
                        NSMakeRange(location, [scannedString length] - location)];
                if (key && value && [key length] > 0 && [value length] > 0) {
                    if (!others) {
                        others = [NSMutableDictionary dictionary];
                    }
                    [others setObject:value forKey:key];
                }
            }
            else if (!firstOne) {
                firstOne = scannedString;
            }
        }
        
        [scanner scanCharactersFromSet:chSet intoString:nil];
    }
    
    *dict = others;
    return firstOne;
}

- (void)handlePortMessage:(NSPortMessage*)message
{
    // Get message info
    unsigned    msgid;
    id          component;
    msgid = [message msgid];
    component = [[message components] objectAtIndex:0];
    
    // Get client
    id  client;
    client = [self client];
    
    switch (msgid) {
    case _SRHTTPURLHeadDone: {
        // Get status code
        long    statusCode = 0;
        curl_easy_getinfo(_CURL, CURLINFO_HTTP_CODE, &statusCode);
        
        // For Not Modified status
        if (statusCode == 304) { // Not Modified
            // Notify cached resposne
            [self _notifyWithCachedResponse];
            break;
        }
        
        // Get MIME type
        NSString*       MIMEType;
        NSDictionary*   otherTypes = nil;
        MIMEType = [_headers HTTPPropertyForKey:@"Content-Type"];
        if (MIMEType) {
            MIMEType = [self _firstElementOfValue:MIMEType others:&otherTypes];
        }
        
        // Get expected content length
        int expectedContentLength = -1;
        if ([_headers HTTPPropertyForKey:@"Content-Length"]) {
            expectedContentLength = [[_headers HTTPPropertyForKey:@"Content-Length"] intValue];
        }
        
        // Get text encoding name
        NSString*   textEncodingName = nil;
        if (otherTypes) {
            textEncodingName = [otherTypes HTTPPropertyForKey:@"charset"];
        }
        
        // Creaet HTTP response
        _response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL] 
                MIMEType:MIMEType 
                expectedContentLength:expectedContentLength 
                textEncodingName:textEncodingName];
        if (statusCode > 0) {
            [_response setStatusCode:statusCode];
        }
        [_response setAllHeaderFields:_headers];
        
        // Get location
        NSString*   location;
        NSURL*      locationURL = nil;
        location = [_headers HTTPPropertyForKey:@"Location"];
        if (location) {
            locationURL = [NSURL URLWithString:location];
        }
        
        // For redirection
        if (locationURL && 
            (statusCode == 300 || // Multiple Choices 
             statusCode == 301 || // Moved Permanently
             statusCode == 302 || // Found
             statusCode == 303 || // See Other
             statusCode == 307))   // Temporary Redirect
        {
            // Create redirected request
            if (_request != _initialRequest) {
                [_request release];
            }
            _request = [[NSURLRequest requestWithURL:locationURL 
                    cachePolicy:[_initialRequest cachePolicy] 
                    timeoutInterval:[_initialRequest timeoutInterval]] retain];
            
            // Notify redirection
            if ([client respondsToSelector:@selector(URLProtocol:wasRedirectedToRequest:redirectResponse:)]) {
                [client URLProtocol:self wasRedirectedToRequest:_request redirectResponse:_response];
            }
        }
        else {
            // Notify response reception
            if ([client respondsToSelector:@selector(URLProtocol:didReceiveResponse:cacheStoragePolicy:)]) {
                [client URLProtocol:self 
                        didReceiveResponse:_response 
                        cacheStoragePolicy:NSURLCacheStorageAllowed];
            }
        }
        break;
    }
    case _SRHTTPURLReceivedBody: {
        [_data appendData:component];
        
        // Notify body reception
        if ([client respondsToSelector:@selector(URLProtocol:didLoadData:)]) {
            [[self client] URLProtocol:self didLoadData:component];
        }
        break;
    }
    case _SRHTTPURLFinished: {
        // Notify completion
        if ([client respondsToSelector:@selector(URLProtocolDidFinishLoading:)]) {
            [client URLProtocolDidFinishLoading:self];
        }
        break;
    }
    }
}

@end
