sftpgo/internal/httpd/api_defender.go

94 lines
2.4 KiB
Go
Raw Permalink Normal View History

// Copyright (C) 2019 Nicola Murino
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
2021-01-02 18:33:24 +00:00
package httpd
import (
2021-06-07 19:52:43 +00:00
"encoding/hex"
2021-01-02 18:33:24 +00:00
"errors"
"fmt"
"net"
"net/http"
"github.com/go-chi/render"
"github.com/drakkan/sftpgo/v2/internal/common"
"github.com/drakkan/sftpgo/v2/internal/dataprovider"
"github.com/drakkan/sftpgo/v2/internal/util"
2021-01-02 18:33:24 +00:00
)
2021-06-07 19:52:43 +00:00
func getDefenderHosts(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
hosts, err := common.GetDefenderHosts()
if err != nil {
sendAPIResponse(w, r, err, "", getRespStatus(err))
return
}
2021-06-08 11:24:28 +00:00
if hosts == nil {
render.JSON(w, r, make([]dataprovider.DefenderEntry, 0))
2021-06-08 11:24:28 +00:00
return
}
render.JSON(w, r, hosts)
2021-06-07 19:52:43 +00:00
}
func getDefenderHostByID(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
2021-06-07 19:52:43 +00:00
ip, err := getIPFromID(r)
if err != nil {
sendAPIResponse(w, r, err, "", http.StatusBadRequest)
return
}
host, err := common.GetDefenderHost(ip)
if err != nil {
sendAPIResponse(w, r, err, "", getRespStatus(err))
return
}
render.JSON(w, r, host)
}
func deleteDefenderHostByID(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
2021-06-07 19:52:43 +00:00
ip, err := getIPFromID(r)
if err != nil {
sendAPIResponse(w, r, err, "", http.StatusBadRequest)
return
}
if !common.DeleteDefenderHost(ip) {
sendAPIResponse(w, r, nil, "Not found", http.StatusNotFound)
return
}
sendAPIResponse(w, r, nil, "OK", http.StatusOK)
}
func getIPFromID(r *http.Request) (string, error) {
decoded, err := hex.DecodeString(getURLParam(r, "id"))
if err != nil {
return "", errors.New("invalid host id")
}
ip := util.BytesToString(decoded)
2021-06-07 19:52:43 +00:00
err = validateIPAddress(ip)
if err != nil {
return "", err
}
return ip, nil
}
2021-01-02 18:33:24 +00:00
func validateIPAddress(ip string) error {
if net.ParseIP(ip) == nil {
return fmt.Errorf("ip address %q is not valid", ip)
2021-01-02 18:33:24 +00:00
}
return nil
}