/*
 * Copyright (C) 2015 by the University of Southern California
 * $Id: client_proxy.hh 24214 2015-05-28 06:43:52Z liangzhu $
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License,
 * version 2, 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.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. 
 * 
 */

#ifndef CLIENT_PROXY_HH
#define CLIENT_PROXY_HH

#include <atomic>
#include <mutex>
#include <vector>
#include <string>
#include <netinet/in.h>
#include <event2/event.h>
#include <openssl/ssl.h>
#include "safe_map.hh"
#include "dns_util.h"

#define WRITE_TIMEOUT  60
#define READ_TIMEOUT   60

class client_proxy {
public:
  client_proxy(const char *, int, const char *, int, int);
  ~client_proxy();
  void start();

private:
  std::string svr_ip;
  std::string lis_ip;
  int svr_port;
  int lis_port;
  int conn_type;
  
  struct sockaddr_in svr_addr;
  struct sockaddr_in my_addr;
  struct event_base *base;
  struct bufferevent *svr_bev;
  std::mutex mtx_svr_bev;

  std::vector<struct event *> event_list;
  safe_map<uint16_t, client_t *> *clt_map;

  int svr_fd;
  int my_udp_fd;
  int my_tcp_fd;

  SSL_CTX *ssl_ctx;
  SSL *ssl;

  void run_tcp();
  void run_ssl();
  void clt_read_ev_init();
  void connect_server();
  void do_starttls();
  bool setup_tcp_event();
  std::atomic<bool> starttls_success;

  void renew_ssl(struct bufferevent *);

  static void starttls_event_cb_helper(struct bufferevent *, short, void *);
  void starttls_event_cb(struct bufferevent *, short);

  static void starttls_read_cb_helper(struct bufferevent *, void *);
  void starttls_read_cb(struct bufferevent *);

  static void svr_read_cb_helper(struct bufferevent *, void *);
  void svr_read_cb(struct bufferevent *);

  static void ssl_event_cb_helper(struct bufferevent *, short, void *);
  void ssl_event_cb(struct bufferevent *, short);

  static void clt_read_cb_helper(evutil_socket_t, short, void *);
  void clt_read_cb(evutil_socket_t, short);

  static void tcp_event_cb_helper(struct bufferevent *, short, void *);
  void tcp_event_cb(struct bufferevent *, short);
};

#endif //CLIENT_PROXY_HH
