/* OpenVAS-Client
 * $Id$
 * Description: Writing and reading one or more certificates to / from 
 * a file that roughly uses freedesktop.org specifications (Glibs GKeyFile).
 *
 * Authors:
 * Felix Wolfsteller <felix.wolfsteller@intevation.de>
 *
 * Copyright:
 * Copyright (C) 2009 Greenbone Networks GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2,
 * or, at your option, any later version as published by the Free
 * Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <fcntl.h> /* for open */
#include <unistd.h> /* for close */

#include "certificate.h" /* for certificate_t */
#include "openvas_certificate_file.h"

#define KEY_CERT_OWNERNAME "ownername" /**< Key used to store ownernames.*/
#define KEY_CERT_TRUSTED "trusted" /**< Key used to store trust level.*/

/** @todo Resolve workaround, real i18n */
#define _(abc) abc

/** @todo Re-enable error reporting (currently commented, show_error) */

/**
 * \file
 * Functions to "(de)serialize" one or more certificates to or from a
 * file.
 * The public key will neither be stored nor loaded.
 * Makes use of GLibs GKeyFile mechanism. The files will and have to look like:
 * <pre>
  [C3B468D2288C68B9D526452248479FF648DB4530]
  ownername=\sOpenVAS Transfer Integrity
  trusted=false
  </pre>
 * where there can be more than one entry as shown above.
 * This follows a freeddesktop.org specification and is parsed using GLibs
 * GKeyFile.
 */

/**
 * @brief Adds a certificate to a GKeyFile.
 *
 * Use as a callback function (e.g. for foreachs of a hashtable).
 *
 * @param fpr Fingerprint of certificate, used as group name.
 * @param value Pointer to a certificate_t struct.
 * @param file Pointer to GKeyFile.
 */
static void
add_cert_to_file (char* fpr, certificate_t* cert, GKeyFile* file)
{
  if(fpr == NULL || file == NULL || cert == NULL)
    return;

  g_key_file_set_string (file, fpr, KEY_CERT_OWNERNAME, cert->owner);
  g_key_file_set_boolean (file, fpr, KEY_CERT_TRUSTED, cert->trusted);
}

/**
 * @brief Writes all certificates found in \ref certs
 * @brief (might be NULL) to the file \ref filename.
 *
 * Certificates can be retrieved from that file calling 
 * openvas_certificate_file_read.
 *
 * @param context Context of which the certificates shall be stored.
 * @param filename Filename used to save the certificates.
 *
 * @return TRUE when successfull, FALSE otherwise.
 *
 * @see openvas_certificate_file_read
 */
gboolean openvas_certificate_file_write (GHashTable* certs, char* filename)
{
  if (filename == NULL)
    return FALSE;

  int fd;
  GKeyFile* key_file = g_key_file_new();
  gchar* keyfile_data;
  gsize data_length;
  GError* err = NULL;

  g_key_file_set_comment(key_file, NULL, NULL, 
                         "This file was generated by OpenVAS and shall not be edited manually.",
                         &err);
  if (err != NULL)
    {
    //show_error(_("Error adding comment to key file: %s"), err->message);
    g_error_free(err);
    g_key_file_free(key_file);
    return FALSE;
    }

  // Add all certificates to GKeyFile.
  if(certs != NULL)
    {
      g_hash_table_foreach (certs, (GHFunc) add_cert_to_file, key_file);
    } // (else file content is comment only)

  // Write GKeyFile to filesystem.
  fd = open (filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
  if(!fd)
    {
    //show_error(_("Error accessing certificate file for report."));
    g_key_file_free(key_file);
    return FALSE;
    }

  keyfile_data = g_key_file_to_data(key_file, &data_length, &err);
  if(err != NULL)
    {
    //show_error(_("Error exporting key file: %s"), err->message);
    g_error_free(err);
    g_key_file_free(key_file);
    close(fd);
    return FALSE;
    }

  write(fd, keyfile_data, data_length);
  close(fd);

  g_key_file_free(key_file);

  return TRUE;
}

/**
 * @brief Reads all certificates found in file \ref filename, creates
 * @brief certificate_t structs, stores these in a GHashTable (with
 * @brief fingerprints as keys) and returns the hashtable.
 *
 * Certificates can be written to that file calling 
 * openvas_certificate_file_write.
 *
 * @param filename Path to file to read certificates from.
 *
 * @return GHashTable with fingerprint/certificate_t* as key/values or
 *         NULL in case of an error.
 *
 * @see openvas_certificate_file_write
 */
GHashTable* openvas_certificate_file_read(char* filename)
{
  gchar** fprs;
  gsize length;
  GKeyFile* key_file = g_key_file_new();
  GError* err        = NULL;
  GHashTable* certificates = g_hash_table_new_full(g_str_hash, g_str_equal,
                             NULL, (GDestroyNotify) certificate_free);

  g_key_file_load_from_file(key_file, filename, G_KEY_FILE_NONE, &err);

  if(err != NULL)
    {
    g_hash_table_destroy(certificates);
    //show_error(_("Error loading certificate store %s: %s"), filename,
    //                                                        err->message);
    g_key_file_free(key_file);
    return NULL;
    }

  fprs = g_key_file_get_groups(key_file, &length);

  // Read Certificate information from file and add entry to hashtable.
  int i = 0;
  for(i = 0; i < length; i++)
    {
    if(fprs[i] == NULL || fprs[i] == '\0')
      continue;
    // Init a certificate
    gchar* ownername = g_key_file_get_string(key_file, fprs[i], 
                                            KEY_CERT_OWNERNAME, &err);
    gboolean trusted = g_key_file_get_boolean(key_file, fprs[i], 
                                              KEY_CERT_TRUSTED, &err);
    certificate_t* cert = certificate_create_full (fprs[i], ownername, NULL, trusted);
    if (ownername == NULL || err != NULL)
      {
      if (ownername != NULL)
        g_free (ownername);
      certificate_free (cert);
      continue;
      }

    g_hash_table_insert (certificates, cert->fingerprint, cert);
    }

  g_key_file_free(key_file);

  return certificates;
}
