/*
 * Part of Very Secure FTPd
 * Licence: GPL v2
 * Author: Chris Evans
 * Extended: Dmitriy Balashov
 * opts.c
 *
 * Routines to handle OPTS.
 */

#include "ftpcodes.h"
#include "ftpcmdio.h"
#include "session.h"
#include "tunables.h"
#include "charconv.h"

void
handle_opts(struct vsf_session* p_sess)
{
  struct mystr opts = INIT_MYSTR;
  struct mystr prm  = INIT_MYSTR;
  
  str_upper(&p_sess->ftp_arg_str);
  str_copy(&opts, &p_sess->ftp_arg_str);
  str_split_char(&opts, &prm, ' ');
  
  if (tunable_convert_charset_enable && str_equal_text(&opts, "UTF8"))
  {
    if (str_equal_text(&prm, "ON"))
    {
      p_sess->remote_charset = vsf_charconv_codepage(VSFTP_CP_UTF8);
      p_sess->enable_convertion = vsf_charconv_avail_convertion(tunable_local_codepage, p_sess->remote_charset);
      vsf_cmdio_write(p_sess, FTP_OPTSOK, "UTF8 option is On.");
    }
    else
    if (str_equal_text(&prm, "OFF"))
    {
      p_sess->remote_charset = tunable_remote_codepage;
      p_sess->enable_convertion = vsf_charconv_avail_convertion(tunable_local_codepage, p_sess->remote_charset);
      vsf_cmdio_write(p_sess, FTP_OPTSOK, "UTF8 option is Off.");
    }
    else
    {
      vsf_cmdio_write(p_sess, FTP_BADOPTS, "Invalid UTF8 option.");
    }
  } 
  else
  if (str_equal_text(&opts, "CP"))
  {
    if (vsf_charconv_avail_convertion(tunable_local_codepage, vsf_charconv_codepage(str_getbuf(&prm))))
    {
      vsf_cmdio_write(p_sess, FTP_OPTSOK, "Codepage changed.");
      p_sess->remote_charset = vsf_charconv_codepage(str_getbuf(&prm));
      p_sess->enable_convertion = 1;
    }
    else
    {
      vsf_cmdio_write(p_sess, FTP_BADOPTS, "Bad codepage defined");
    }
  }
  else
  if (str_equal_text(&p_sess->ftp_arg_str, "UTF8 ON"))
  {
    vsf_cmdio_write(p_sess, FTP_OPTSOK, "Always in UTF8 mode.");
  }
  else
  {
    vsf_cmdio_write(p_sess, FTP_BADOPTS, "Option not understood.");
  }

  str_free(&opts);
  str_free(&prm);
}
