/*

Copyright (C) 2015, 2016 Olaf Till <i7tiol@t-online.de>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

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, see <http://www.gnu.org/licenses/>.

*/

#include "parallel-gnutls.h"

static int assert_dir (std::string &path)
{
  file_stat stat (path);

  if (! stat.is_dir () && mkdir (path.c_str (), 0700))
    return -1;
  else
    return 0;
}

DEFUN_DLD (parallel_generate_srp_data, args, ,
           "-*- texinfo -*-\n\
@deftypefn {Loadable Function} {} parallel_generate_srp_data (@var{username})\n\
@deftypefnx {Loadable Function} {} parallel_generate_srp_data (@var{username}, @var{options})\n\
Prompts for a password (press enter for a random password) and writes TLS-SRP authentication files into the directory given by:\n\
\n\
@code{fullfile (a = pkg (\"prefix\"), \"parallel-srp-data\")}\n\
\n\
Server files are placed in subdirectory @code{server}. By default, a\n\
client authentication file is placed in subdirectory\n\
@code{client}. The latter contains the given @var{username} and the\n\
cleartext password. You do not need this file if you prefer to be\n\
prompted for username and password at connection time. In this case,\n\
you can prevent the client authentication file from being written by\n\
passing as the argument @var{options} a structure with a value of\n\
@code{false} in the field @code{unattended}.\n\
\n\
For authentication, subdir @code{server}, and possibly subdir\n\
@code{client}, have to be placed together with their contents at the\n\
respective machines. They can either be placed under the directory\n\
given by:\n\
\n\
@code{fullfile (OCTAVE_HOME (), \"share\", \"octave\", \"parallel-srp-data\")}\n\
\n\
or -- which might be the same directory -- under:\n\
\n\
@code{fullfile (a = pkg (\"prefix\"), \"parallel-srp-data\")}\n\
\n\
Files in the former directory will take precedence over those in the\n\
latter. The contents of the files @code{passwd} and @code{user_passwd}\n\
(if present) must be kept secret.\n\
\n\
This function zeroizes sensitive data before releasing its memory. Due\n\
to usage of external libraries, however, it still can't be excluded\n\
that sensitive data is still on the swap device after application\n\
shutdown.\n\
\n\
@seealso{pconnect, pserver, reval, psend, precv, sclose, select_sockets}\n\
@end deftypefn")
{
  std::string fname ("parallel_generate_srp_data");

  octave_value_list retval;

  if (args.length () < 1 || args.length () > 2)
    {
      print_usage ();

      return retval;
    }

  // get username
  std::string username;

  CHECK_ERROR (username = args(0).string_value (), retval,
               "%s: first argument can not be converted to a string",
               fname.c_str ());

  // default options
  bool clientfile (true);

  // get options, if any
  if (args.length () == 2)
    {
      octave_scalar_map options;

      CHECK_ERROR (options = args(1).scalar_map_value (), retval,
                   "%s: could not convert second argument to scalar structure",
                   fname.c_str ());

      octave_value tmp;

      // write client data to file
      tmp = options.contents ("unattended");

      if (tmp.is_defined ())
        {
          CHECK_ERROR (clientfile = tmp.bool_value (), retval,
                       "%s: could not convert option 'unattended' to bool",
                       fname.c_str ());
        }
    } // args.length () == 2

  // define directories and filenames

  octave_value_list f_args (1);
  f_args(0) = octave_value ("prefix");

  octave_value_list f_ret;

  CHECK_ERROR (f_ret = feval ("pkg", f_args, 1), retval,
               "%s: could not get prefix from pkg", fname.c_str ());

  std::string basedir;

  CHECK_ERROR (basedir = f_ret(0).string_value (), retval,
               "%s: could not convert output of pkg ('prefix') to string)",
               fname.c_str ());

  basedir = basedir + file_ops::dir_sep_str () +
    "parallel-srp-data" + file_ops::dir_sep_str ();
  std::string serverdir = basedir + "server" + file_ops::dir_sep_str ();
  std::string clientdir = basedir + "client" + file_ops::dir_sep_str ();
  
  if (assert_dir (basedir))
    {
      error ("%s: directory %s does not exist and can't be created, consider creating it manually",
             fname.c_str (), basedir.c_str ());

      return retval;
    }

  if (assert_dir (serverdir))
    {
      error ("%s: directory %s does not exist and can't be created, consider creating it manually",
             fname.c_str (), serverdir.c_str ());

      return retval;
    }

  if (clientfile && assert_dir (clientdir))
    {
      error ("%s: directory %s does not exist and can't be created, consider creating it manually",
             fname.c_str (), clientdir.c_str ());

      return retval;
    }

  std::string passwd = serverdir + "passwd";
  std::string passwd_conf = serverdir + "passwd.conf";
  std::string user_passwd = clientdir + "user_passwd";

  // get password; not supposed to be free'd again, don't do it
  sensitive_string user_password
    (getpass ("password (default is random password): "));
  if (! user_password.good ())
    {
      error ("%s: could not read password", fname.c_str ());

      return retval;
    }

  if (user_password.get_size () == 0)
    {
      // no use making a random password if it is not written to a file
      if (! clientfile)
        {
          error ("%s: if the password is not provided by the user, option 'unattended' must not be false",
                 fname.c_str ());

          return retval;
        }

      // get a random password of 10 bytes, each restricted to 128 values
      user_password.fill (10);

      if (! user_password.good ())
        {
          error ("%s: could not get random password", fname.c_str ());

          return retval;
        }
    }

  // get random salt of 10 bytes, each restricted to 128 values
  sensitive_string salt (10);
  if (! salt.good ())
    {
      error ("%s: could not get random salt", fname.c_str ());

      return retval;
    }

  // let gnutls compute the srp verifier
  verifier v (username.c_str (), user_password.get_string (), &salt.get_val ());
  if (! v.good ())
    {
      error ("%s: could not generate verifier", fname.c_str ());

      return retval;
    }

  // if desired, write client authentication information
  if (clientfile)
    {
      octave_parallel_stream cfio
        (new octave_parallel_file_streambuf
         (user_passwd.c_str (), O_WRONLY | O_CREAT | O_TRUNC, 0600));

      if (! cfio.good ())
        {
          error ("%s: could not open client file %s",
                 fname.c_str (), user_passwd.c_str ());

          return retval;
        }

      cfio.get_ostream () << username.c_str () << " "
                          << user_password.get_string () << "\n";

      cfio.close ();

      if (! cfio.good ())
        {
          error ("%s: could not write client file", fname.c_str ());

          return retval;
        }
    }

  // password not needed anymore, zero and free it (but only zero it
  // and not free it if it was made with 'getpass'
  user_password.free_val ();

  // write server passwd file or append if it exists
  std::string group_index ("1");
  if (true)
    {
      srp_base64_encode v_enc (&(v.get_val ()));
      srp_base64_encode salt_enc (&(salt.get_val ()));
      if (! (v_enc.good () && salt_enc.good ()))
        return retval;

      octave_parallel_stream spfio
        (new octave_parallel_file_streambuf
         (passwd.c_str (), O_WRONLY | O_CREAT | O_APPEND, 0600));

      if (! spfio.good ())
        {
          error ("%s: could not open server passwd file %s",
                 fname.c_str (), passwd.c_str ());

          return retval;
        }

      spfio.get_ostream () << username.c_str () << ":"
                           << v_enc.get_string () << ":"
                           << salt_enc.get_string () << ":"
                           << group_index.c_str () << "\n";

      spfio.close ();

      if (! spfio.good ())
        {
          error ("%s: could not write server passwd file", fname.c_str ());

          return retval;
        }
    }

  // verifier and salt not needed anymore, zero and free them
  v.free_val ();
  salt.free_val ();

  // write server passwd.conf file
  srp_base64_encode prime_enc (&gnutls_srp_2048_group_prime);

  octave_parallel_stream scfio
    (new octave_parallel_file_streambuf
     (passwd_conf.c_str (), O_WRONLY | O_CREAT | O_TRUNC, 0600));

      if (! scfio.good ())
        {
          error ("%s: could not open server passwd.conf file %s",
                 fname.c_str (), passwd_conf.c_str ());

          return retval;
        }

      scfio.get_ostream () << group_index.c_str () << ":"
                           << prime_enc.get_string () << ":"
                           << (int) *((unsigned char *)
                                      gnutls_srp_2048_group_generator.data)
                           << "\n";

      scfio.close ();

      if (! scfio.good ())
        {
          error ("%s: could not write server passwd.conf file", fname.c_str ());

          return retval;
        }

  return retval;
}
