/*
 * Part of Very Secure FTPd
 * Licence: GPL v2
 * Author: Dmitriy Balashov
 * http.c
 *
 * Routines to handle HTTP.
 */

#include "session.h"
#include "access.h"
#include "tunables.h"
#include "charconv.h"
#include "filestr.h"
#include "str.h"
#include "strlist.h"
#include "ftpcmdio.h"
#include "ls.h"
#include "sysutil.h"
#include "sysstr.h"
#include "logging.h"
#include "defs.h"
#include "utility.h"
#include "postlogin.h"
#include "http_msg.h"
#include "http_str.h"

enum EResourceType
{
  ResTypeNotFound = -1,
  ResTypeFile,
  ResType_Dir,
  ResTypeDir
};

static void http_error(struct vsf_session* p_sess, const enum EVSFHttpMsgType p_type);
static void http_html_content(struct vsf_session* p_sess, const char* response, const struct mystr* body);
static void http_header_print(struct vsf_session* p_sess, const char* response);
static enum EResourceType http_check_resource(struct vsf_session* p_sess, filesize_t* p_size);
static enum EResourceType http_request_resource_type(struct vsf_session* p_sess, filesize_t* p_size);
static void http_handle_send(struct vsf_session* p_sess, filesize_t p_size);
static void http_handle_browse(struct vsf_session* p_sess);

static char* err_403_forbidden = "403 Forbidden";
static char* err_404_not_found = "404 Not Found";
static char* err_200_ok        = "200 OK";

void
handle_http(struct vsf_session* p_sess)
{
  /* Warning: Doesn't respect cmds_allowed etc. because there is currently only
   * one command (GET)!
   * HTTP likely doesn't respect other important FTP options. I don't think
   * logging works.
   */
  if (!tunable_download_enable)
  {
    bug("HTTP needs download - fix your config");
  }
  /* Eat the HTTP headers, which we don't care about. */

  do
  {
    vsf_cmdio_get_cmd_and_arg(p_sess, &p_sess->ftp_cmd_str,
                              &p_sess->ftp_arg_str, 1, 1);
  }
  while (!str_isempty(&p_sess->ftp_cmd_str) ||
         !str_isempty(&p_sess->ftp_arg_str));

  if (!p_sess->is_anonymous)
  {
    http_error(p_sess, kVSFHttpMsgType403Serv);
  }

  /* Split the path from the HTTP/1.x */
  str_split_char(&p_sess->http_get_arg, &p_sess->ftp_arg_str, ' ');
  str_unescape(&p_sess->http_get_arg);

  static filesize_t p_size;
  enum EResourceType p_res_type = http_check_resource(p_sess, &p_size);

  switch (p_res_type)
  {
    case ResTypeDir:
      if (!tunable_http_browse || str_chdir(&p_sess->http_get_arg) != 0)
      {
        http_error(p_sess, kVSFHttpMsgType403);
      }
      break;
    case ResTypeNotFound:
      http_error(p_sess, kVSFHttpMsgType404);
      break;
    default:
      break;
  }

  if (p_res_type == ResTypeDir)
  {
    http_handle_browse(p_sess);
  }
  else
  {
    http_handle_send(p_sess, p_size);
  }

  if (vsf_log_entry_pending(p_sess))
  {
    vsf_log_do_log(p_sess, 0);
  }
  vsf_sysutil_exit(0);
}

static void
http_error(struct vsf_session* p_sess, const enum EVSFHttpMsgType p_type)
{
  static char* response;
  static struct mystr p_tpl = INIT_MYSTR;
  static struct mystr p_res = INIT_MYSTR;

  switch (p_type)
  {
    case kVSFHttpMsgType403Serv:
      response = err_403_forbidden;
      break;
    case kVSFHttpMsgType403:
      response = err_403_forbidden;
      break;
    case kVSFHttpMsgType404:
      response = err_404_not_found;
      break;
    default:
      bug("Bad HTTP error code");
      break;
  }

  str_alloc_text(&p_tpl, vsf_http_messages_get(p_type));
  str_process_template(p_sess, &p_res, &p_tpl, 0, 0, vsf_sysutil_get_time_sec(), 0);
  http_html_content(p_sess, response, &p_res);
}

static void
http_html_content(struct vsf_session* p_sess,
                  const char* response,
                  const struct mystr* body)
{
  http_header_print(p_sess, response);
  vsf_cmdio_write_raw_quiet(p_sess, "Content-Type: text/html\r\n");

  vsf_cmdio_write_raw_quiet(p_sess, "Content-Length: ");
  vsf_cmdio_write_raw_quiet(p_sess, vsf_sysutil_filesize_t_to_str(str_getlen(body)));
  vsf_cmdio_write_raw_quiet(p_sess, "\r\n\r\n");
  vsf_cmdio_write_raw_quiet(p_sess, str_getbuf(body));

  vsf_sysutil_exit(0);
}


static void
http_header_print(struct vsf_session* p_sess, const char* response)
{
  static const char* hdr = "\r\n"
                           "Server: vsftpd\r\n"
                           "Connection: close\r\n"
                           "X-Frame-Options: SAMEORIGIN\r\n"
                           "X-Content-Type-Options: nosniff\r\n";

  vsf_cmdio_write_raw_quiet(p_sess, "HTTP/1.0 ");
  vsf_cmdio_write_raw_quiet(p_sess, response);
  vsf_cmdio_write_raw_quiet(p_sess, hdr);
}

static enum EResourceType
http_check_resource(struct vsf_session* p_sess, filesize_t* p_size)
{
  enum EResourceType ret = http_request_resource_type(p_sess, p_size);

  if (ret == ResType_Dir)
  {
    str_chdir(&p_sess->http_get_arg);
    str_getcwd(&p_sess->http_get_arg);
    http_header_print(p_sess, "302 Found");
    vsf_cmdio_write_raw_quiet(p_sess, "Location: ");
    vsf_cmdio_write_raw_quiet(p_sess, str_getbuf(&p_sess->http_get_arg));
    vsf_cmdio_write_raw_quiet(p_sess, "/\r\n\r\n");

    vsf_sysutil_exit(0);
  }

  return ret;
}

static enum EResourceType
http_request_resource_type(struct vsf_session* p_sess, filesize_t* p_size)
{
  static struct vsf_sysutil_statbuf* p_statbuf;
  static struct mystr path = INIT_MYSTR;
  int retval = 0;
  enum EResourceType ret = ResTypeFile;

  if (str_equal_text(&p_sess->http_get_arg, "/"))
  {
    ret = ResTypeDir;
  }
  else
  {
    if (str_get_char_at(&p_sess->http_get_arg, str_getlen(&p_sess->http_get_arg) - 1) == '/')
    {
      ret++; // _Dir
      str_left(&p_sess->http_get_arg, &path, str_getlen(&p_sess->http_get_arg) - 1);
    }
    else
    {
      str_copy(&path, &p_sess->http_get_arg);
    }

    retval = str_stat(&path, &p_statbuf);
    if (retval == 0)
    {
      if (vsf_sysutil_statbuf_is_dir(p_statbuf))
      {
        ret++;
        struct str_locate_result locate = str_locate_text(&path, "..");
        if (locate.found && ret == ResTypeDir)
        {
          ret--;
        }
      }
      else
      {
        if (ret != ResTypeFile)
        {
          ret = ResTypeNotFound;
        }
        else
        {
          *p_size = vsf_sysutil_statbuf_get_size(p_statbuf);
        }
      }
    }
    else
    {
      ret = ResTypeNotFound;
    }
  }

  if ((ret == ResTypeDir || ret == ResTypeFile) &&
      !vsf_access_check_file(&p_sess->http_get_arg))
  {
    http_error(p_sess, kVSFHttpMsgType403);
  }
  if (ret == ResTypeDir && tunable_http_default_index)
  {
    struct mystr old = INIT_MYSTR;
    str_alloc_text(&old, str_getbuf(&p_sess->http_get_arg));
    str_append_text(&p_sess->http_get_arg, tunable_http_default_index);
    ret = http_request_resource_type(p_sess, p_size);
    if (ret != ResTypeFile)
    {
      ret = ResTypeDir;
      str_alloc_text(&p_sess->http_get_arg, str_getbuf(&old));
    }
    str_empty(&old);
  }
  if (ret == ResTypeFile)
  {
    int opened_file;
    opened_file = str_open(&p_sess->http_get_arg, kVSFSysStrOpenReadOnly);
    if (vsf_sysutil_retval_is_error(opened_file))
    {
      http_error(p_sess, kVSFHttpMsgType403);
    }
    vsf_sysutil_close(opened_file);
  }

  str_empty(&path);

  return ret;
}

static void
http_handle_send(struct vsf_session* p_sess, filesize_t p_size)
{
  http_header_print(p_sess, err_200_ok);
  str_copy(&p_sess->ftp_arg_str, &p_sess->http_get_arg);

  {
    struct str_locate_result locate;
    locate = str_locate_text_reverse(&p_sess->ftp_arg_str, ".");
    if (locate.found == 1)
    {
      str_right(&p_sess->ftp_arg_str, &p_sess->ftp_cmd_str, str_getlen(&p_sess->ftp_arg_str) - locate.index - 1);
    }
    else
    {
      str_empty(&p_sess->ftp_cmd_str);
    }
  }

  str_upper(&p_sess->ftp_cmd_str);
  if (str_equal_text(&p_sess->ftp_cmd_str, "HTML") ||
      str_equal_text(&p_sess->ftp_cmd_str, "HTM"))
  {
    vsf_cmdio_write_raw_quiet(p_sess, "Content-Type: text/html\r\n");
  }
  else
  {
    vsf_cmdio_write_raw_quiet(p_sess, "Content-Type: dunno\r\n");
  }
  vsf_cmdio_write_raw_quiet(p_sess, "Content-Length: ");
  vsf_cmdio_write_raw_quiet(p_sess, vsf_sysutil_filesize_t_to_str(p_size));
  vsf_cmdio_write_raw_quiet(p_sess, "\r\n\r\n");
  p_sess->is_ascii = 0;
  p_sess->restart_pos = 0;
  process_http_retr(p_sess);
}

static void http_handle_browse(struct vsf_session* p_sess)
{
  struct vsf_sysutil_dir* p_dir = 0;
  static struct vsf_sysutil_statbuf* s_p_dirstat;
  int dir_allow_read = 1;
  struct mystr_list dir_list = INIT_STRLIST;

  p_dir = str_opendir(&p_sess->http_get_arg);
  if (p_dir && tunable_anon_world_readable_only)
  {
    vsf_sysutil_dir_stat(p_dir, &s_p_dirstat);
    if (!vsf_sysutil_statbuf_is_readable_other(s_p_dirstat))
    {
      dir_allow_read = 0;
    }
  }
  if (p_dir != 0 && dir_allow_read)
  {
    static struct mystr s_option_str = INIT_MYSTR;
    static struct mystr s_filter_str = INIT_MYSTR;

    vsf_ls_populate_dir_list(p_sess, &dir_list, 0, p_dir, &p_sess->http_get_arg,
                             &s_option_str, &s_filter_str, 1, 1);
  }
  if (p_dir)
  {
    vsf_sysutil_closedir(p_dir);
  }
  if (!dir_allow_read)
  {
    http_error(p_sess, kVSFHttpMsgType403);
  }
  else
  {
    static struct mystr p_tpl = INIT_MYSTR;
    static struct mystr p_res = INIT_MYSTR;

    str_alloc_text(&p_tpl, vsf_http_messages_get(kVSFHttpMsgType200Browse));
    str_process_template(p_sess, &p_res, &p_tpl, 0, 0, vsf_sysutil_get_time_sec(), &dir_list);
    str_list_free(&dir_list);
    http_html_content(p_sess, err_200_ok, &p_res);
  }
}
