/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#include "dnsdist.hh"
#include "sstuff.hh"
#include "ext/json11/json11.hpp"
#include "ext/incbin/incbin.h"
#include "dolog.hh"
#include <thread>
#include <sstream>
#include <yahttp/yahttp.hpp>
#include "namespaces.hh"
#include <sys/time.h>
#include <sys/resource.h>
#include "ext/incbin/incbin.h"
#include "htmlfiles.h"
#include "base64.hh"
#include "gettime.hh"

bool g_apiReadWrite{false};
std::string g_apiConfigDirectory;

static bool apiWriteConfigFile(const string& filebasename, const string& content)
{
  if (!g_apiReadWrite) {
    errlog("Not writing content to %s since the API is read-only", filebasename);
    return false;
  }

  if (g_apiConfigDirectory.empty()) {
    vinfolog("Not writing content to %s since the API configuration directory is not set", filebasename);
    return false;
  }

  string filename = g_apiConfigDirectory + "/" + filebasename + ".conf";
  ofstream ofconf(filename.c_str());
  if (!ofconf) {
    errlog("Could not open configuration fragment file '%s' for writing: %s", filename, stringerror());
    return false;
  }
  ofconf << "-- Generated by the REST API, DO NOT EDIT" << endl;
  ofconf << content << endl;
  ofconf.close();
  return true;
}

static void apiSaveACL(const NetmaskGroup& nmg)
{
  vector<string> vec;
  g_ACL.getLocal()->toStringVector(&vec);

  string acl;
  for(const auto& s : vec) {
    if (!acl.empty()) {
      acl += ", ";
    }
    acl += "\"" + s + "\"";
  }

  string content = "setACL({" + acl + "})";
  apiWriteConfigFile("acl", content);
}

static bool checkAPIKey(const YaHTTP::Request& req, const string& expectedApiKey)
{
  if (expectedApiKey.empty()) {
    return false;
  }

  const auto header = req.headers.find("x-api-key");
  if (header != req.headers.end()) {
    return (header->second == expectedApiKey);
  }

  return false;
}

static bool checkWebPassword(const YaHTTP::Request& req, const string &expected_password)
{
  static const char basicStr[] = "basic ";

  const auto header = req.headers.find("authorization");

  if (header != req.headers.end() && toLower(header->second).find(basicStr) == 0) {
    string cookie = header->second.substr(sizeof(basicStr) - 1);

    string plain;
    B64Decode(cookie, plain);

    vector<string> cparts;
    stringtok(cparts, plain, ":");

    if (cparts.size() == 2) {
      return cparts[1] == expected_password;
    }
  }

  return false;
}

static bool isAnAPIRequest(const YaHTTP::Request& req)
{
  return req.url.path.find("/api/") == 0;
}

static bool isAnAPIRequestAllowedWithWebAuth(const YaHTTP::Request& req)
{
  return req.url.path == "/api/v1/servers/localhost";
}

static bool isAStatsRequest(const YaHTTP::Request& req)
{
  return req.url.path == "/jsonstat";
}

static bool compareAuthorization(const YaHTTP::Request& req, const string &expected_password, const string& expectedApiKey)
{
  if (isAnAPIRequest(req)) {
    /* Access to the API requires a valid API key */
    if (checkAPIKey(req, expectedApiKey)) {
      return true;
    }

    return isAnAPIRequestAllowedWithWebAuth(req) && checkWebPassword(req, expected_password);
  }

  if (isAStatsRequest(req)) {
    /* Access to the stats is allowed for both API and Web users */
    return checkAPIKey(req, expectedApiKey) || checkWebPassword(req, expected_password);
  }

  return checkWebPassword(req, expected_password);
}

static bool isMethodAllowed(const YaHTTP::Request& req)
{
  if (req.method == "GET") {
    return true;
  }
  if (req.method == "PUT" && g_apiReadWrite) {
    if (req.url.path == "/api/v1/servers/localhost/config/allow-from") {
      return true;
    }
  }
  return false;
}

static void handleCORS(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  const auto origin = req.headers.find("Origin");
  if (origin != req.headers.end()) {
    if (req.method == "OPTIONS") {
      /* Pre-flight request */
      if (g_apiReadWrite) {
        resp.headers["Access-Control-Allow-Methods"] = "GET, PUT";
      }
      else {
        resp.headers["Access-Control-Allow-Methods"] = "GET";
      }
      resp.headers["Access-Control-Allow-Headers"] = "Authorization, X-API-Key";
    }

    resp.headers["Access-Control-Allow-Origin"] = origin->second;

    if (isAStatsRequest(req) || isAnAPIRequestAllowedWithWebAuth(req)) {
      resp.headers["Access-Control-Allow-Credentials"] = "true";
    }
  }
}

static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optional<std::map<std::string, std::string> >& customHeaders)
{
  static const std::vector<std::pair<std::string, std::string> > headers = {
    { "X-Content-Type-Options", "nosniff" },
    { "X-Frame-Options", "deny" },
    { "X-Permitted-Cross-Domain-Policies", "none" },
    { "X-XSS-Protection", "1; mode=block" },
    { "Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'" },
  };

  for (const auto& h : headers) {
    if (customHeaders) {
      const auto& custom = customHeaders->find(h.first);
      if (custom != customHeaders->end()) {
        continue;
      }
    }
    resp.headers[h.first] = h.second;
  }
}

static void addCustomHeaders(YaHTTP::Response& resp, const boost::optional<std::map<std::string, std::string> >& customHeaders)
{
  if (!customHeaders)
    return;

  for (const auto& c : *customHeaders) {
    if (!c.second.empty()) {
      resp.headers[c.first] = c.second;
    }
  }
}

template<typename T>
static json11::Json::array someResponseRulesToJson(GlobalStateHolder<vector<T>>* someResponseRules)
{
  using namespace json11;
  Json::array responseRules;
  int num=0;
  auto localResponseRules = someResponseRules->getLocal();
  for(const auto& a : *localResponseRules) {
    Json::object rule{
      {"id", num++},
      {"uuid", boost::uuids::to_string(a.d_id)},
      {"matches", (double)a.d_rule->d_matches},
      {"rule", a.d_rule->toString()},
      {"action", a.d_action->toString()},
    };
    responseRules.push_back(rule);
  }
  return responseRules;
}

static void connectionThread(int sock, ComboAddress remote, string password, string apiKey, const boost::optional<std::map<std::string, std::string> >& customHeaders)
{
  using namespace json11;
  vinfolog("Webserver handling connection from %s", remote.toStringWithPort());

  try {
    YaHTTP::AsyncRequestLoader yarl;
    YaHTTP::Request req;
    bool finished = false;

    yarl.initialize(&req);
    while(!finished) {
      int bytes;
      char buf[1024];
      bytes = read(sock, buf, sizeof(buf));
      if (bytes > 0) {
        string data = string(buf, bytes);
        finished = yarl.feed(data);
      } else {
        // read error OR EOF
        break;
      }
    }
    yarl.finalize();

    string command=req.getvars["command"];

    req.getvars.erase("_"); // jQuery cache buster

    YaHTTP::Response resp;
    resp.version = req.version;
    const string charset = "; charset=utf-8";

    addCustomHeaders(resp, customHeaders);
    addSecurityHeaders(resp, customHeaders);
    /* indicate that the connection will be closed after completion of the response */
    resp.headers["Connection"] = "close";

    /* no need to send back the API key if any */
    resp.headers.erase("X-API-Key");

    if(req.method == "OPTIONS") {
      /* the OPTIONS method should not require auth, otherwise it breaks CORS */
      handleCORS(req, resp);
      resp.status=200;
    }
    else if (!compareAuthorization(req, password, apiKey)) {
      YaHTTP::strstr_map_t::iterator header = req.headers.find("authorization");
      if (header != req.headers.end())
        errlog("HTTP Request \"%s\" from %s: Web Authentication failed", req.url.path, remote.toStringWithPort());
      resp.status=401;
      resp.body="<h1>Unauthorized</h1>";
      resp.headers["WWW-Authenticate"] = "basic realm=\"PowerDNS\"";

    }
    else if(!isMethodAllowed(req)) {
      resp.status=405;
    }
    else if(req.url.path=="/jsonstat") {
      handleCORS(req, resp);
      resp.status=200;

      if(command=="stats") {
        auto obj=Json::object {
          { "packetcache-hits", 0},
          { "packetcache-misses", 0},
          { "over-capacity-drops", 0 },
          { "too-old-drops", 0 },
          { "server-policy", g_policy.getLocal()->name}
        };

        for(const auto& e : g_stats.entries) {
          if(const auto& val = boost::get<DNSDistStats::stat_t*>(&e.second))
            obj.insert({e.first, (double)(*val)->load()});
          else if (const auto& dval = boost::get<double*>(&e.second))
            obj.insert({e.first, (**dval)});
          else
            obj.insert({e.first, (double)(*boost::get<DNSDistStats::statfunction_t>(&e.second))(e.first)});
        }
        Json my_json = obj;
        resp.body=my_json.dump();
        resp.headers["Content-Type"] = "application/json";
      }
      else if(command=="dynblocklist") {
        Json::object obj;
        auto nmg = g_dynblockNMG.getLocal();
        struct timespec now;
        gettime(&now);
        for(const auto& e: *nmg) {
          if(now < e->second.until ) {
            Json::object thing{
              {"reason", e->second.reason},
              {"seconds", (double)(e->second.until.tv_sec - now.tv_sec)},
              {"blocks", (double)e->second.blocks},
              {"action", DNSAction::typeToString(e->second.action) }
            };
            obj.insert({e->first.toString(), thing});
          }
        }

        auto smt = g_dynblockSMT.getLocal();
        smt->visit([&now,&obj](const SuffixMatchTree<DynBlock>& node) {
            if(now <node.d_value.until) {
              string dom("empty");
              if(!node.d_value.domain.empty())
                dom = node.d_value.domain.toString();
              Json::object thing{
                {"reason", node.d_value.reason},
                {"seconds", (double)(node.d_value.until.tv_sec - now.tv_sec)},
                {"blocks", (double)node.d_value.blocks},
                {"action", DNSAction::typeToString(node.d_value.action) }
              };
              obj.insert({dom, thing});
          }
        });



        Json my_json = obj;
        resp.body=my_json.dump();
        resp.headers["Content-Type"] = "application/json";
      }
      else if(command=="ebpfblocklist") {
        Json::object obj;
#ifdef HAVE_EBPF
        struct timespec now;
        gettime(&now);
        for (const auto& dynbpf : g_dynBPFFilters) {
          std::vector<std::tuple<ComboAddress, uint64_t, struct timespec> > addrStats = dynbpf->getAddrStats();
          for (const auto& entry : addrStats) {
            Json::object thing
            {
              {"seconds", (double)(std::get<2>(entry).tv_sec - now.tv_sec)},
              {"blocks", (double)(std::get<1>(entry))}
            };
            obj.insert({std::get<0>(entry).toString(), thing });
          }
        }
#endif /* HAVE_EBPF */
        Json my_json = obj;
        resp.body=my_json.dump();
        resp.headers["Content-Type"] = "application/json";
      }
      else {
        resp.status=404;
      }
    }
    else if(req.url.path=="/api/v1/servers/localhost") {
      handleCORS(req, resp);
      resp.status=200;

      Json::array servers;
      auto localServers = g_dstates.getLocal();
      int num=0;
      for(const auto& a : *localServers) {
	string status;
	if(a->availability == DownstreamState::Availability::Up) 
	  status = "UP";
	else if(a->availability == DownstreamState::Availability::Down) 
	  status = "DOWN";
	else 
	  status = (a->upStatus ? "up" : "down");

	Json::array pools;
	for(const auto& p: a->pools)
	  pools.push_back(p);

	Json::object server{ 
	  {"id", num++},
	  {"name", a->name},
          {"address", a->remote.toStringWithPort()},
          {"state", status},
          {"qps", (double)a->queryLoad},
          {"qpsLimit", (double)a->qps.getRate()},
          {"outstanding", (double)a->outstanding},
          {"reuseds", (double)a->reuseds},
          {"weight", (double)a->weight},
          {"order", (double)a->order},
          {"pools", pools},
          {"latency", (double)(a->latencyUsec/1000.0)},
          {"queries", (double)a->queries},
          {"sendErrors", (double)a->sendErrors},
          {"dropRate", (double)a->dropRate}
        };

        /* sending a latency for a DOWN server doesn't make sense */
        if (a->availability == DownstreamState::Availability::Down) {
          server["latency"] = nullptr;
        }

	servers.push_back(server);
      }

      Json::array frontends;
      num=0;
      for(const auto& front : g_frontends) {
        if (front->udpFD == -1 && front->tcpFD == -1)
          continue;
        Json::object frontend{
          { "id", num++ },
          { "address", front->local.toStringWithPort() },
          { "udp", front->udpFD >= 0 },
          { "tcp", front->tcpFD >= 0 },
          { "queries", (double) front->queries.load() }
        };
        frontends.push_back(frontend);
      }

      Json::array pools;
      auto localPools = g_pools.getLocal();
      num=0;
      for(const auto& pool : *localPools) {
        const auto& cache = pool.second->packetCache;
        Json::object entry {
          { "id", num++ },
          { "name", pool.first },
          { "serversCount", (double) pool.second->countServers(false) },
          { "cacheSize", (double) (cache ? cache->getMaxEntries() : 0) },
          { "cacheEntries", (double) (cache ? cache->getEntriesCount() : 0) },
          { "cacheHits", (double) (cache ? cache->getHits() : 0) },
          { "cacheMisses", (double) (cache ? cache->getMisses() : 0) },
          { "cacheDeferredInserts", (double) (cache ? cache->getDeferredInserts() : 0) },
          { "cacheDeferredLookups", (double) (cache ? cache->getDeferredLookups() : 0) },
          { "cacheLookupCollisions", (double) (cache ? cache->getLookupCollisions() : 0) },
          { "cacheInsertCollisions", (double) (cache ? cache->getInsertCollisions() : 0) },
          { "cacheTTLTooShorts", (double) (cache ? cache->getTTLTooShorts() : 0) }
        };
        pools.push_back(entry);
      }

      Json::array rules;
      auto localRules = g_rulactions.getLocal();
      num=0;
      for(const auto& a : *localRules) {
	Json::object rule{
          {"id", num++},
          {"uuid", boost::uuids::to_string(a.d_id)},
          {"matches", (double)a.d_rule->d_matches},
          {"rule", a.d_rule->toString()},
          {"action", a.d_action->toString()},
          {"action-stats", a.d_action->getStats()}
        };
	rules.push_back(rule);
      }
      
      auto responseRules = someResponseRulesToJson(&g_resprulactions);
      auto cacheHitResponseRules = someResponseRulesToJson(&g_cachehitresprulactions);
      auto selfAnsweredResponseRules = someResponseRulesToJson(&g_selfansweredresprulactions);

      string acl;

      vector<string> vec;
      g_ACL.getLocal()->toStringVector(&vec);

      for(const auto& s : vec) {
        if(!acl.empty()) acl += ", ";
        acl+=s;
      }
      string localaddresses;
      for(const auto& loc : g_locals) {
        if(!localaddresses.empty()) localaddresses += ", ";
        localaddresses += std::get<0>(loc).toStringWithPort();
      }
 
      Json my_json = Json::object {
        { "daemon_type", "dnsdist" },
        { "version", VERSION},
        { "servers", servers},
        { "frontends", frontends },
        { "pools", pools },
        { "rules", rules},
        { "response-rules", responseRules},
        { "cache-hit-response-rules", cacheHitResponseRules},
        { "self-answered-response-rules", selfAnsweredResponseRules},
        { "acl", acl},
        { "local", localaddresses}
      };
      resp.headers["Content-Type"] = "application/json";
      resp.body=my_json.dump();
    }
    else if(req.url.path=="/api/v1/servers/localhost/statistics") {
      handleCORS(req, resp);
      resp.status=200;

      Json::array doc;
      for(const auto& item : g_stats.entries) {
        if(const auto& val = boost::get<DNSDistStats::stat_t*>(&item.second)) {
          doc.push_back(Json::object {
              { "type", "StatisticItem" },
              { "name", item.first },
              { "value", (double)(*val)->load() }
            });
        }
        else if (const auto& dval = boost::get<double*>(&item.second)) {
          doc.push_back(Json::object {
              { "type", "StatisticItem" },
              { "name", item.first },
              { "value", (**dval) }
            });
        }
        else {
          doc.push_back(Json::object {
              { "type", "StatisticItem" },
              { "name", item.first },
              { "value", (double)(*boost::get<DNSDistStats::statfunction_t>(&item.second))(item.first) }
            });
        }
      }
      Json my_json = doc;
      resp.body=my_json.dump();
      resp.headers["Content-Type"] = "application/json";
    }
    else if(req.url.path=="/api/v1/servers/localhost/config") {
      handleCORS(req, resp);
      resp.status=200;

      Json::array doc;
      typedef boost::variant<bool, double, std::string> configentry_t;
      std::vector<std::pair<std::string, configentry_t> > configEntries {
        { "acl", g_ACL.getLocal()->toString() },
        { "control-socket", g_serverControl.toStringWithPort() },
        { "ecs-override", g_ECSOverride },
        { "ecs-source-prefix-v4", (double) g_ECSSourcePrefixV4 },
        { "ecs-source-prefix-v6", (double)  g_ECSSourcePrefixV6 },
        { "fixup-case", g_fixupCase },
        { "max-outstanding", (double) g_maxOutstanding },
        { "server-policy", g_policy.getLocal()->name },
        { "stale-cache-entries-ttl", (double) g_staleCacheEntriesTTL },
        { "tcp-recv-timeout", (double) g_tcpRecvTimeout },
        { "tcp-send-timeout", (double) g_tcpSendTimeout },
        { "truncate-tc", g_truncateTC },
        { "verbose", g_verbose },
        { "verbose-health-checks", g_verboseHealthChecks }
      };
      for(const auto& item : configEntries) {
        if (const auto& bval = boost::get<bool>(&item.second)) {
          doc.push_back(Json::object {
              { "type", "ConfigSetting" },
              { "name", item.first },
              { "value", *bval }
          });
        }
        else if (const auto& sval = boost::get<string>(&item.second)) {
          doc.push_back(Json::object {
              { "type", "ConfigSetting" },
              { "name", item.first },
              { "value", *sval }
          });
        }
        else if (const auto& dval = boost::get<double>(&item.second)) {
          doc.push_back(Json::object {
              { "type", "ConfigSetting" },
              { "name", item.first },
              { "value", *dval }
          });
        }
      }
      Json my_json = doc;
      resp.body=my_json.dump();
      resp.headers["Content-Type"] = "application/json";
    }
    else if(req.url.path=="/api/v1/servers/localhost/config/allow-from") {
      handleCORS(req, resp);

      resp.headers["Content-Type"] = "application/json";
      resp.status=200;

      if (req.method == "PUT") {
        std::string err;
        Json doc = Json::parse(req.body, err);

        if (!doc.is_null()) {
          NetmaskGroup nmg;
          auto aclList = doc["value"];
          if (aclList.is_array()) {

            for (auto value : aclList.array_items()) {
              try {
                nmg.addMask(value.string_value());
              } catch (NetmaskException &e) {
                resp.status = 400;
                break;
              }
            }

            if (resp.status == 200) {
              infolog("Updating the ACL via the API to %s", nmg.toString());
              g_ACL.setState(nmg);
              apiSaveACL(nmg);
            }
          }
          else {
            resp.status = 400;
          }
        }
        else {
          resp.status = 400;
        }
      }
      if (resp.status == 200) {
        Json::array acl;
        vector<string> vec;
        g_ACL.getLocal()->toStringVector(&vec);

        for(const auto& s : vec) {
          acl.push_back(s);
        }

        Json::object obj{
          { "type", "ConfigSetting" },
          { "name", "allow-from" },
          { "value", acl }
        };
        Json my_json = obj;
        resp.body=my_json.dump();
      }
    }
    else if(!req.url.path.empty() && g_urlmap.count(req.url.path.c_str()+1)) {
      resp.body.assign(g_urlmap[req.url.path.c_str()+1]);
      vector<string> parts;
      stringtok(parts, req.url.path, ".");
      if(parts.back() == "html")
        resp.headers["Content-Type"] = "text/html" + charset;
      else if(parts.back() == "css")
        resp.headers["Content-Type"] = "text/css" + charset;
      else if(parts.back() == "js")
        resp.headers["Content-Type"] = "application/javascript" + charset;
      else if(parts.back() == "png")
        resp.headers["Content-Type"] = "image/png";
      resp.status=200;
    }
    else if(req.url.path=="/") {
      resp.body.assign(g_urlmap["index.html"]);
      resp.headers["Content-Type"] = "text/html" + charset;
      resp.status=200;
    }
    else {
      // cerr<<"404 for: "<<req.url.path<<endl;
      resp.status=404;
    }

    std::ostringstream ofs;
    ofs << resp;
    string done;
    done=ofs.str();
    writen2(sock, done.c_str(), done.size());

    close(sock);
    sock = -1;
  }
  catch(const YaHTTP::ParseError& e) {
    vinfolog("Webserver thread died with parse error exception while processing a request from %s: %s", remote.toStringWithPort(), e.what());
    close(sock);
  }
  catch(const std::exception& e) {
    errlog("Webserver thread died with exception while processing a request from %s: %s", remote.toStringWithPort(), e.what());
    close(sock);
  }
  catch(...) {
    errlog("Webserver thread died with exception while processing a request from %s", remote.toStringWithPort());
    close(sock);
  }
}
void dnsdistWebserverThread(int sock, const ComboAddress& local, const std::string& password, const std::string& apiKey, const boost::optional<std::map<std::string, std::string> >& customHeaders)
{
  warnlog("Webserver launched on %s", local.toStringWithPort());
  for(;;) {
    try {
      ComboAddress remote(local);
      int fd = SAccept(sock, remote);
      vinfolog("Got connection from %s", remote.toStringWithPort());
      std::thread t(connectionThread, fd, remote, password, apiKey, customHeaders);
      t.detach();
    }
    catch(std::exception& e) {
      errlog("Had an error accepting new webserver connection: %s", e.what());
    }
  }
}
