//
//  UA_Base64.h
//
//  Created by Matt Gallagher on 2009/06/03.
//  Copyright 2009 Matt Gallagher. All rights reserved.
//  Modified by Urban Airship to be used as a stand alone class instead of a
//  category.
//
//  This software is provided 'as-is', without any express or implied
//  warranty. In no event will the authors be held liable for any damages
//  arising from the use of this software. Permission is granted to anyone to
//  use this software for any purpose, including commercial applications, and to
//  alter it and redistribute it freely, subject to the following restrictions:
//
//  1. The origin of this software must not be misrepresented; you must not
//     claim that you wrote the original software. If you use this software
//     in a product, an acknowledgment in the product documentation would be
//     appreciated but is not required.
//  2. Altered source versions must be plainly marked as such, and must not be
//     misrepresented as being the original software.
//  3. This notice may not be removed or altered from any source
//     distribution.
//

#import "Base64.h"

//
// Mapping from 6 bit pattern to ASCII character.
//
static u_char _encodingMap[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

//
// Definition for "masked-out" areas of the _decodingMap mapping
//
static const u_char xx = 65;

//
// Mapping from ASCII character to 6 bit pattern.
//
static const u_char _decodingMap[256] =
{
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, 62, xx, xx, xx, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, xx, xx, xx, xx, xx, xx,
    xx,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, xx, xx, xx, xx, xx,
    xx, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx,
    xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx
};

//
// Fundamental sizes of the binary and base64 encode/decode units in bytes
//
#define BINARY_UNIT_SIZE 3
#define BASE64_UNIT_SIZE 4

//
// returns the encoded buffer. Must be free'd by caller. Length is given by
//    target_size.
//
char *base64_encode(const void *source, size_t source_size, size_t *target_size, Boolean webSafely) {
    //
    // Byte accurate calculation of final buffer size, include space for a terminating zero
    //
    const char *src = (const char *)source;
    const size_t oddmentSize = source_size % BINARY_UNIT_SIZE;
    const size_t massSize = source_size - oddmentSize;
    size_t outBufferSize = source_size + 1;
    
    if (oddmentSize > 0) {
        outBufferSize += BINARY_UNIT_SIZE;
    }
    
    //
    // Allocate the output buffer
    //
    char *outBuffer = (char *)malloc(outBufferSize);
    
    size_t i = 0;
    size_t j = 0;
    
    for (; i < massSize; i += BINARY_UNIT_SIZE) {
        //
        // Inner loop: turn 48 bytes into 64 base64 characters
        //
        outBuffer[j++] = _encodingMap[(src[i] & 0xFC) >> 2];
        outBuffer[j++] = _encodingMap[((src[i] & 0x03) << 4) | ((src[i + 1] & 0xF0) >> 4)];
        outBuffer[j++] = _encodingMap[((src[i + 1] & 0x0F) << 2) | ((src[i + 2] & 0xC0) >> 6)];
        outBuffer[j++] = _encodingMap[src[i + 2] & 0x3F];
    }
    
    if (2 == oddmentSize) {
        //
        // Handle the single '=' case
        //
        outBuffer[j++] = _encodingMap[(src[i] & 0xFC) >> 2];
        outBuffer[j++] = _encodingMap[((src[i] & 0x03) << 4) | ((src[i + 1] & 0xF0) >> 4)];
        outBuffer[j++] = _encodingMap[(src[i + 1] & 0x0F) << 2];
        outBuffer[j++] = '=';
        
    } else if (1 == oddmentSize) {
        //
        // Handle the double '=' case
        //
        outBuffer[j++] = _encodingMap[(src[i] & 0xFC) >> 2];
        outBuffer[j++] = _encodingMap[(src[i] & 0x03) << 4];
        outBuffer[j++] = '=';
        outBuffer[j++] = '=';
    }
    outBuffer[j] = 0;
    
    //
    // Set the output source_size and return the buffer
    //
    if (target_size) {
        *target_size = j;
    }
    return outBuffer;
}

//
// returns the decoded buffer. Must be free'd by caller. Length is given by
//    target_size.
//
void *base64_decode(const char *source, size_t source_size, size_t *target_size) {
    if (-1 == source_size) {
        source_size = strlen(source);
    }
    
    const size_t oddmentSize = source_size % BASE64_UNIT_SIZE;
    const size_t massSize = source_size - oddmentSize;
    size_t outBufferSize = massSize + 1;
    
    if (oddmentSize > 0) {
        outBufferSize += BASE64_UNIT_SIZE;
    }
    
    u_char *outBuffer = (u_char *)malloc(outBufferSize);
    u_char unitBlock[BASE64_UNIT_SIZE];
    size_t j = 0;
    size_t unitIndex = 0;
    
    for (size_t i = 0; i < source_size; ++ i) {
        const u_char decode = _decodingMap[source[i]];
        
        if (xx != decode) {
            unitBlock[unitIndex ++] = decode;
            
            if (BASE64_UNIT_SIZE == unitIndex) {
                outBuffer[j ++] = (unitBlock[0] << 2) | (unitBlock[1] >> 4);
                outBuffer[j ++] = (unitBlock[1] << 4) | (unitBlock[2] >> 2);
                outBuffer[j ++] = (unitBlock[2] << 6) | unitBlock[3];
                unitIndex = 0;
            }
        }
    }
    
    if (unitIndex >= 2) {
        outBuffer[j ++] = (unitBlock[0] << 2) | (unitBlock[1] >> 4);
    }
    if (unitIndex >= 3) {
        outBuffer[j ++] = (unitBlock[1] << 4) | (unitBlock[2] >> 2);
    }
    
    if (target_size) {
        *target_size = j;
    }
    return outBuffer;
}

//
// dataDecodedFromBase64String:
//
// Creates an NSData object containing the base64 decoded representation of
// the base64 string 'aString'
//
// Parameters:
//    aString - the base64 string to decode
//
// returns the autoreleased NSData representation of the base64 string
//
NSData* dataDecodedFromBase64String(NSString* aString) {
    size_t target_size = 0;
    const char *utf8 = [aString UTF8String];
    void *outBuffer = base64_decode(utf8, strlen(utf8), &target_size);
    NSData *result = [[NSData alloc] initWithBytesNoCopy:outBuffer length:target_size freeWhenDone:YES];
    
    return result;
}

//
// base64EncodedString
//
// Creates an NSString object that contains the base 64 encoding of the
// receiver's data. Lines are broken at 64 characters long.
//
// returns an autoreleased NSString being the base 64 representation of the
//    receiver.
//
NSString* stringEncodedByBase64FromBytes(const u_char* bytes, size_t size, Boolean webSafely)
{
    size_t target_size = 0;
    char *outBuffer = base64_encode(bytes, size, &target_size, webSafely);
    NSString *result = [[NSString alloc] initWithBytesNoCopy:outBuffer length:target_size encoding:NSUTF8StringEncoding freeWhenDone:YES];
    return result;
}
