for update IPTable reduce logic

This commit is contained in:
2024-11-13 17:04:28 +00:00
parent eb0a7d6b34
commit 623d7b93e0

View File

@@ -1,449 +1,451 @@
package server package server
import ( import (
b64 "encoding/base64" b64 "encoding/base64"
"errors" "encoding/json"
"fmt" "errors"
"github.com/Akilan1999/p2p-rendering-computation/client/clientIPTable" "fmt"
"github.com/Akilan1999/p2p-rendering-computation/config" "github.com/Akilan1999/p2p-rendering-computation/client/clientIPTable"
"github.com/Akilan1999/p2p-rendering-computation/p2p" "github.com/Akilan1999/p2p-rendering-computation/config"
"github.com/Akilan1999/p2p-rendering-computation/p2p/frp" "github.com/Akilan1999/p2p-rendering-computation/p2p"
"github.com/Akilan1999/p2p-rendering-computation/server/docker" "github.com/Akilan1999/p2p-rendering-computation/p2p/frp"
"github.com/gin-gonic/gin" "github.com/Akilan1999/p2p-rendering-computation/server/docker"
"net/http" "github.com/gin-gonic/gin"
"os/user" "io/ioutil"
"strconv" "net/http"
"time" "os/user"
"strconv"
"time"
) )
type ReverseProxy struct { type ReverseProxy struct {
IPAddress string IPAddress string
Port string Port string
} }
// ReverseProxies Reverse to the map such as ReverseProxies[<domain nane>]ReverseProxy type // ReverseProxies Reverse to the map such as ReverseProxies[<domain nane>]ReverseProxy type
var ReverseProxies map[string]ReverseProxy var ReverseProxies map[string]ReverseProxy
func Server() (*gin.Engine, error) { func Server() (*gin.Engine, error) {
r := gin.Default() r := gin.Default()
// "The make function allocates and initializes a hash map data // "The make function allocates and initializes a hash map data
//structure and returns a map value that points to it. //structure and returns a map value that points to it.
//The specifics of that data structure are an implementation //The specifics of that data structure are an implementation
//detail of the runtime and are not specified by the language itself." //detail of the runtime and are not specified by the language itself."
// source: https://go.dev/blog/maps // source: https://go.dev/blog/maps
ReverseProxies = make(map[string]ReverseProxy) ReverseProxies = make(map[string]ReverseProxy)
//Get Server port based on the config file //Get Server port based on the config file
config, err := config.ConfigInit(nil, nil) config, err := config.ConfigInit(nil, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// update IPTable with new port and ip address and update ip table // update IPTable with new port and ip address and update ip table
var ProxyIpAddr p2p.IpAddress var ProxyIpAddr p2p.IpAddress
var lowestLatencyIpAddress p2p.IpAddress var lowestLatencyIpAddress p2p.IpAddress
// Gets default information of the server // Gets default information of the server
r.GET("/server_info", func(c *gin.Context) { r.GET("/server_info", func(c *gin.Context) {
c.JSON(http.StatusOK, ServerInfo()) c.JSON(http.StatusOK, ServerInfo())
}) })
// Speed test with 50 mbps // Speed test with 50 mbps
r.GET("/50", func(c *gin.Context) { r.GET("/50", func(c *gin.Context) {
// Get Path from config // Get Path from config
c.File(config.SpeedTestFile) c.File(config.SpeedTestFile)
}) })
// Route build to do a speed test // Route build to do a speed test
r.GET("/upload", func(c *gin.Context) { r.GET("/upload", func(c *gin.Context) {
file, _ := c.FormFile("file") file, _ := c.FormFile("file")
// Upload the file to specific dst. // Upload the file to specific dst.
// c.SaveUploadedFile(file, dst) // c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
}) })
//Gets Ip Table from server node //Gets Ip Table from server node
r.POST("/IpTable", func(c *gin.Context) { r.POST("/IpTable", func(c *gin.Context) {
//// Getting IPV4 address of client // Getting IPV4 address of client
//var ClientHost p2p.IpAddress //var ClientHost p2p.IpAddress
// //
//if p2p.Ip4or6(c.ClientIP()) == "version 6" { //if p2p.Ip4or6(c.ClientIP()) == "version 6" {
// ClientHost.Ipv6 = c.ClientIP() // ClientHost.Ipv6 = c.ClientIP()
//} else { //} else {
// ClientHost.Ipv4 = c.ClientIP() // ClientHost.Ipv4 = c.ClientIP()
//} //}
//
//// Variable to store IP table information
//var IPTable p2p.IpAddresses
//
//// Receive file from POST request
//body, err := c.FormFile("json")
//if err != nil {
// c.String(http.StatusOK, fmt.Sprint(err))
//}
//
//// Open file
//open, err := body.Open()
//if err != nil {
// c.String(http.StatusOK, fmt.Sprint(err))
//}
//
//// Open received file
//file, err := ioutil.ReadAll(open)
//if err != nil {
// c.String(http.StatusOK, fmt.Sprint(err))
//}
//
//json.Unmarshal(file, &IPTable)
//
////Add Client IP address to IPTable struct
//IPTable.IpAddress = append(IPTable.IpAddress, ClientHost)
//
//// Runs speed test to return only servers in the IP table pingable
//err = IPTable.SpeedTestUpdatedIPTable()
//if err != nil {
// c.String(http.StatusOK, fmt.Sprint(err))
//}
// Reads IP addresses from ip table // Variable to store IP table information
IpAddresses, err := p2p.ReadIpTable() var IPTable p2p.IpAddresses
if err != nil {
c.String(http.StatusOK, fmt.Sprint(err))
}
c.JSON(http.StatusOK, IpAddresses) // Receive file from POST request
}) body, err := c.FormFile("json")
if err != nil {
c.String(http.StatusOK, fmt.Sprint(err))
}
// Starts docker container in server // Open file
r.GET("/startcontainer", func(c *gin.Context) { open, err := body.Open()
// Get Number of ports to open and whether to use GPU or not if err != nil {
Ports := c.DefaultQuery("ports", "0") c.String(http.StatusOK, fmt.Sprint(err))
GPU := c.DefaultQuery("GPU", "false") }
ContainerName := c.DefaultQuery("ContainerName", "")
BaseImage := c.DefaultQuery("BaseImage", "")
PublicKey := c.DefaultQuery("PublicKey", "")
var PortsInt int
if PublicKey == "" { // Open received file
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", "Publickey not passed")) file, err := ioutil.ReadAll(open)
} if err != nil {
c.String(http.StatusOK, fmt.Sprint(err))
}
PublicKeyDecoded, err := b64.StdEncoding.DecodeString(PublicKey) json.Unmarshal(file, &IPTable)
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
// Convert Get Request value to int //Add Client IP address to IPTable struct
fmt.Sscanf(Ports, "%d", &PortsInt) //IPTable.IpAddress = append(IPTable.IpAddress, ClientHost)
fmt.Println(string(PublicKeyDecoded[:])) // Runs speed test to return only servers in the IP table pingable
err = IPTable.SpeedTestUpdatedIPTable()
if err != nil {
c.String(http.StatusOK, fmt.Sprint(err))
}
// Creates container and returns-back result to // Reads IP addresses from ip table
// access container IpAddresses, err := p2p.ReadIpTable()
resp, err := docker.BuildRunContainer(PortsInt, GPU, ContainerName, BaseImage, string(PublicKeyDecoded[:])) if err != nil {
c.String(http.StatusOK, fmt.Sprint(err))
}
if err != nil { c.JSON(http.StatusOK, IpAddresses)
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) })
}
// Ensures that FRP is triggered only if a proxy address is provided // Starts docker container in server
if ProxyIpAddr.Ipv4 != "" && c.Request.Host != "localhost:"+config.ServerPort && c.Request.Host != "0.0.0.0:"+config.ServerPort { r.GET("/startcontainer", func(c *gin.Context) {
resp, err = frp.StartFRPCDockerContainer(ProxyIpAddr.Ipv4, lowestLatencyIpAddress.ServerPort, resp) // Get Number of ports to open and whether to use GPU or not
if err != nil { Ports := c.DefaultQuery("ports", "0")
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) GPU := c.DefaultQuery("GPU", "false")
} ContainerName := c.DefaultQuery("ContainerName", "")
} BaseImage := c.DefaultQuery("BaseImage", "")
PublicKey := c.DefaultQuery("PublicKey", "")
var PortsInt int
c.JSON(http.StatusOK, resp) if PublicKey == "" {
}) c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", "Publickey not passed"))
}
//Remove container PublicKeyDecoded, err := b64.StdEncoding.DecodeString(PublicKey)
r.GET("/RemoveContainer", func(c *gin.Context) { if err != nil {
ID := c.DefaultQuery("id", "0") c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
if err := docker.StopAndRemoveContainer(ID); err != nil { }
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.String(http.StatusOK, "success")
})
//Show images available // Convert Get Request value to int
r.GET("/ShowImages", func(c *gin.Context) { fmt.Sscanf(Ports, "%d", &PortsInt)
resp, err := docker.ViewAllContainers()
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.JSON(http.StatusOK, resp)
})
// Request for port no from Server with address fmt.Println(string(PublicKeyDecoded[:]))
r.GET("/FRPPort", func(c *gin.Context) {
port, err := frp.StartFRPProxyFromRandom()
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.String(http.StatusOK, strconv.Itoa(port)) // Creates container and returns-back result to
}) // access container
resp, err := docker.BuildRunContainer(PortsInt, GPU, ContainerName, BaseImage, string(PublicKeyDecoded[:]))
r.GET("/MAPPort", func(c *gin.Context) { if err != nil {
Ports := c.DefaultQuery("port", "0") c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
DomainName := c.DefaultQuery("domain_name", "") }
url, _, err := MapPort(Ports, DomainName)
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.String(http.StatusOK, url) // Ensures that FRP is triggered only if a proxy address is provided
}) if ProxyIpAddr.Ipv4 != "" && c.Request.Host != "localhost:"+config.ServerPort && c.Request.Host != "0.0.0.0:"+config.ServerPort {
resp, err = frp.StartFRPCDockerContainer(ProxyIpAddr.Ipv4, lowestLatencyIpAddress.ServerPort, resp)
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
}
r.GET("/AddProxy", func(c *gin.Context) { c.JSON(http.StatusOK, resp)
DomainName := c.DefaultQuery("domain_name", "") })
ip_address := c.DefaultQuery("ip_address", "")
Ports := c.DefaultQuery("port", "")
if DomainName == "" || ip_address == "" || Ports == "" { //Remove container
c.String(http.StatusInternalServerError, fmt.Sprintf("All get parameters npt provided"+ r.GET("/RemoveContainer", func(c *gin.Context) {
" do ensure domain_name, ip_Address and port no is provided")) ID := c.DefaultQuery("id", "0")
} if err := docker.StopAndRemoveContainer(ID); err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.String(http.StatusOK, "success")
})
err := SaveRegistration(DomainName, ip_address+":"+Ports) //Show images available
if err != nil { r.GET("/ShowImages", func(c *gin.Context) {
c.String(http.StatusInternalServerError, fmt.Sprintf(err.Error())) resp, err := docker.ViewAllContainers()
} if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.JSON(http.StatusOK, resp)
})
//_, ok := ReverseProxies[DomainName] // Request for port no from Server with address
//// To check if the subdomain entry exists r.GET("/FRPPort", func(c *gin.Context) {
//if ok { port, err := frp.StartFRPProxyFromRandom()
// c.String(http.StatusInternalServerError, fmt.Sprintf("The domain entry already exists as a reverse"+ if err != nil {
// " proxy entry")) c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
//} }
//
//// added proxy as a map entry
//ReverseProxies[DomainName] = ReverseProxy{IPAddress: ip_address, Port: Ports}
c.String(http.StatusOK, "Sucess")
}) c.String(http.StatusOK, strconv.Itoa(port))
})
//r.GET("/RemoveProxy", func(c *gin.Context) { r.GET("/MAPPort", func(c *gin.Context) {
// DomainName := c.DefaultQuery("domain_name", "") Ports := c.DefaultQuery("port", "0")
// DomainName := c.DefaultQuery("domain_name", "")
// _, ok := ReverseProxies[DomainName] url, _, err := MapPort(Ports, DomainName)
// if !ok { if err != nil {
// c.String(http.StatusInternalServerError, fmt.Sprintf("Domain name does exist in entries of proxies")) c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
// } else { }
// delete(ReverseProxies, DomainName)
// }
//
//})
// If there is a proxy port specified c.String(http.StatusOK, url)
// then starts the FRP server })
//if config.FRPServerPort != "0" {
// go frp.StartFRPProxyFromRandom()
//}
// Remove nodes currently not pingable r.GET("/AddProxy", func(c *gin.Context) {
clientIPTable.RemoveOfflineNodes() DomainName := c.DefaultQuery("domain_name", "")
ip_address := c.DefaultQuery("ip_address", "")
Ports := c.DefaultQuery("port", "")
table, err := p2p.ReadIpTable() if DomainName == "" || ip_address == "" || Ports == "" {
c.String(http.StatusInternalServerError, fmt.Sprintf("All get parameters npt provided"+
" do ensure domain_name, ip_Address and port no is provided"))
}
// TODO check if IPV6 or Proxy port is specified err := SaveRegistration(DomainName, ip_address+":"+Ports)
// if not update current entry as proxy address if err != nil {
// with appropriate port on IP Table c.String(http.StatusInternalServerError, fmt.Sprintf(err.Error()))
if config.BehindNAT == "True" { }
if err != nil {
return nil, err
}
var lowestLatency int64 //_, ok := ReverseProxies[DomainName]
// random large number //// To check if the subdomain entry exists
lowestLatency = 10000000 //if ok {
// c.String(http.StatusInternalServerError, fmt.Sprintf("The domain entry already exists as a reverse"+
// " proxy entry"))
//}
//
//// added proxy as a map entry
//ReverseProxies[DomainName] = ReverseProxy{IPAddress: ip_address, Port: Ports}
c.String(http.StatusOK, "Sucess")
for i, _ := range table.IpAddress { })
// Checks if the ping is the lowest and if the following node is acting as a proxy
//if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].ProxyPort != "" {
if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].NAT != "" {
lowestLatency = table.IpAddress[i].Latency.Milliseconds()
lowestLatencyIpAddress = table.IpAddress[i]
}
}
// If there is an identified node //r.GET("/RemoveProxy", func(c *gin.Context) {
if lowestLatency != 10000000 { // DomainName := c.DefaultQuery("domain_name", "")
serverPort, err := frp.GetFRPServerPort("http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort) //
if err != nil { // _, ok := ReverseProxies[DomainName]
return nil, err // if !ok {
} // c.String(http.StatusInternalServerError, fmt.Sprintf("Domain name does exist in entries of proxies"))
// Create 3 second delay to allow FRP server to start // } else {
time.Sleep(1 * time.Second) // delete(ReverseProxies, DomainName)
// Starts FRP as a client with // }
proxyPort, err := frp.StartFRPClientForServer(lowestLatencyIpAddress.Ipv4, serverPort, config.ServerPort, "") //
if err != nil { //})
return nil, err
}
// updating with the current proxy address // If there is a proxy port specified
ProxyIpAddr.Ipv4 = lowestLatencyIpAddress.Ipv4 // then starts the FRP server
ProxyIpAddr.ServerPort = proxyPort //if config.FRPServerPort != "0" {
ProxyIpAddr.Name = config.MachineName // go frp.StartFRPProxyFromRandom()
ProxyIpAddr.NAT = "False" //}
ProxyIpAddr.ProxyServer = "False"
ProxyIpAddr.EscapeImplementation = "FRP"
if config.BareMetal { // Remove nodes currently not pingable
_, SSHPort, err := MapPort("22", "") clientIPTable.RemoveOfflineNodes()
if err != nil {
return nil, err
}
ProxyIpAddr.BareMetalSSHPort = SSHPort
}
//ProxyIpAddr.CustomInformationKey = p2p.GenerateHashSHA256(config.IPTableKey) table, err := p2p.ReadIpTable()
// write information back to the IP Table
}
} else { // TODO check if IPV6 or Proxy port is specified
ProxyIpAddr.Ipv4, err = p2p.CurrentPublicIP() // if not update current entry as proxy address
if err != nil { // with appropriate port on IP Table
fmt.Println(err) if config.BehindNAT == "True" {
} if err != nil {
ProxyIpAddr.ServerPort = config.ServerPort return nil, err
ProxyIpAddr.Name = config.MachineName }
ProxyIpAddr.NAT = "False"
if config.ProxyPort != "" {
ProxyIpAddr.ProxyServer = "True"
}
ProxyIpAddr.EscapeImplementation = ""
if config.BareMetal {
ProxyIpAddr.BareMetalSSHPort = "22"
}
} var lowestLatency int64
// random large number
lowestLatency = 10000000
// Get machine username for i, _ := range table.IpAddress {
currentUser, err := user.Current() // Checks if the ping is the lowest and if the following node is acting as a proxy
if err != nil { //if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].ProxyPort != "" {
return nil, err if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].NAT != "" {
} lowestLatency = table.IpAddress[i].Latency.Milliseconds()
// Add username p2prc binary is being run under lowestLatencyIpAddress = table.IpAddress[i]
ProxyIpAddr.MachineUsername = currentUser.Username }
ProxyIpAddr.UnSafeMode = config.UnsafeMode }
// Adds the public key information to the IPTable
// improving transmission of IPTables without the
// entire public key is future work to be improved
// in the P2PRC protocol level (Improving by adding
// UDP with TCP reliability layer).
ProxyIpAddr.PublicKey, err = config.GetPublicKey()
if err != nil { // If there is an identified node
return nil, err if lowestLatency != 10000000 {
} serverPort, err := frp.GetFRPServerPort("http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort)
if err != nil {
return nil, err
}
// Create 3 second delay to allow FRP server to start
time.Sleep(1 * time.Second)
// Starts FRP as a client with
proxyPort, err := frp.StartFRPClientForServer(lowestLatencyIpAddress.Ipv4, serverPort, config.ServerPort, "")
if err != nil {
return nil, err
}
// append the following to the ip table // updating with the current proxy address
table.IpAddress = append(table.IpAddress, ProxyIpAddr) ProxyIpAddr.Ipv4 = lowestLatencyIpAddress.Ipv4
ProxyIpAddr.ServerPort = proxyPort
ProxyIpAddr.Name = config.MachineName
ProxyIpAddr.NAT = "False"
ProxyIpAddr.ProxyServer = "False"
ProxyIpAddr.EscapeImplementation = "FRP"
// Writing results to the IPTable if config.BareMetal {
err = table.WriteIpTable() _, SSHPort, err := MapPort("22", "")
if err != nil { if err != nil {
return nil, err return nil, err
} }
ProxyIpAddr.BareMetalSSHPort = SSHPort
}
// update ip table //ProxyIpAddr.CustomInformationKey = p2p.GenerateHashSHA256(config.IPTableKey)
go func() error { // write information back to the IP Table
err := clientIPTable.UpdateIpTableListClient() }
if err != nil {
fmt.Println(err)
return err
}
return nil
}()
if config.ProxyPort != "" { } else {
go ProxyRun(config.ProxyPort) ProxyIpAddr.Ipv4, err = p2p.CurrentPublicIP()
} if err != nil {
fmt.Println(err)
}
ProxyIpAddr.ServerPort = config.ServerPort
ProxyIpAddr.Name = config.MachineName
ProxyIpAddr.NAT = "False"
if config.ProxyPort != "" {
ProxyIpAddr.ProxyServer = "True"
}
ProxyIpAddr.EscapeImplementation = ""
if config.BareMetal {
ProxyIpAddr.BareMetalSSHPort = "22"
}
// Run gin server on the specified port }
go r.Run(":" + config.ServerPort)
return r, nil // Get machine username
currentUser, err := user.Current()
if err != nil {
return nil, err
}
// Add username p2prc binary is being run under
ProxyIpAddr.MachineUsername = currentUser.Username
ProxyIpAddr.UnSafeMode = config.UnsafeMode
// Adds the public key information to the IPTable
// improving transmission of IPTables without the
// entire public key is future work to be improved
// in the P2PRC protocol level (Improving by adding
// UDP with TCP reliability layer).
ProxyIpAddr.PublicKey, err = config.GetPublicKey()
if err != nil {
return nil, err
}
// append the following to the ip table
table.IpAddress = append(table.IpAddress, ProxyIpAddr)
// Writing results to the IPTable
err = table.WriteIpTable()
if err != nil {
return nil, err
}
// update ip table
go func() error {
err := clientIPTable.UpdateIpTableListClient()
if err != nil {
fmt.Println(err)
return err
}
return nil
}()
if config.ProxyPort != "" {
go ProxyRun(config.ProxyPort)
}
// Run gin server on the specified port
go r.Run(":" + config.ServerPort)
return r, nil
} }
func MapPort(port string, domainName string) (string, string, error) { func MapPort(port string, domainName string) (string, string, error) {
//Get Server port based on the config file //Get Server port based on the config file
config, err := config.ConfigInit(nil, nil) config, err := config.ConfigInit(nil, nil)
if err != nil { if err != nil {
return "", "", err return "", "", err
} }
// update IPTable with new port and ip address and update ip table // update IPTable with new port and ip address and update ip table
var ProxyIpAddr p2p.IpAddress var ProxyIpAddr p2p.IpAddress
var lowestLatencyIpAddress p2p.IpAddress var lowestLatencyIpAddress p2p.IpAddress
clientIPTable.RemoveOfflineNodes() clientIPTable.RemoveOfflineNodes()
table, err := p2p.ReadIpTable() table, err := p2p.ReadIpTable()
if err != nil { if err != nil {
return "", "", err return "", "", err
} }
var lowestLatency int64 var lowestLatency int64
// random large number // random large number
lowestLatency = 10000000 lowestLatency = 10000000
for i, _ := range table.IpAddress { for i, _ := range table.IpAddress {
// Checks if the ping is the lowest and if the following node is acting as a proxy // Checks if the ping is the lowest and if the following node is acting as a proxy
//if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].ProxyPort != "" { //if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].ProxyPort != "" {
if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].NAT != "" { if table.IpAddress[i].Latency.Milliseconds() < lowestLatency && table.IpAddress[i].NAT != "" {
// Filter based on nodes with proxy enabled // Filter based on nodes with proxy enabled
if domainName != "" && table.IpAddress[i].ProxyServer == "True" { if domainName != "" && table.IpAddress[i].ProxyServer == "True" {
lowestLatency = table.IpAddress[i].Latency.Milliseconds() lowestLatency = table.IpAddress[i].Latency.Milliseconds()
lowestLatencyIpAddress = table.IpAddress[i] lowestLatencyIpAddress = table.IpAddress[i]
continue continue
} }
lowestLatency = table.IpAddress[i].Latency.Milliseconds() lowestLatency = table.IpAddress[i].Latency.Milliseconds()
lowestLatencyIpAddress = table.IpAddress[i] lowestLatencyIpAddress = table.IpAddress[i]
} }
} }
// If there is an identified node // If there is an identified node
if lowestLatency != 10000000 { if lowestLatency != 10000000 {
serverPort, err := frp.GetFRPServerPort("http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort) serverPort, err := frp.GetFRPServerPort("http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort)
if err != nil { if err != nil {
return "", "", err return "", "", err
} }
// Create 3 second delay to allow FRP server to start // Create 3 second delay to allow FRP server to start
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
// Starts FRP as a client with // Starts FRP as a client with
proxyPort, err := frp.StartFRPClientForServer(lowestLatencyIpAddress.Ipv4, serverPort, port, "") proxyPort, err := frp.StartFRPClientForServer(lowestLatencyIpAddress.Ipv4, serverPort, port, "")
if err != nil { if err != nil {
return "", "", err return "", "", err
} }
// Doing the proxy mapping for the domain name // Doing the proxy mapping for the domain name
if domainName != "" { if domainName != "" {
fmt.Println("http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort + "/AddProxy?port=" + proxyPort + "&domain_name=" + domainName + "&ip_address=" + lowestLatencyIpAddress.Ipv4) fmt.Println("http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort + "/AddProxy?port=" + proxyPort + "&domain_name=" + domainName + "&ip_address=" + lowestLatencyIpAddress.Ipv4)
URL := "http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort + "/AddProxy?port=" + proxyPort + "&domain_name=" + domainName + "&ip_address=" + lowestLatencyIpAddress.Ipv4 URL := "http://" + lowestLatencyIpAddress.Ipv4 + ":" + lowestLatencyIpAddress.ServerPort + "/AddProxy?port=" + proxyPort + "&domain_name=" + domainName + "&ip_address=" + lowestLatencyIpAddress.Ipv4
//} else { //} else {
// URL = "http://" + IP + ":" + serverPort + "/server_info" // URL = "http://" + IP + ":" + serverPort + "/server_info"
//} //}
http.Get(URL) http.Get(URL)
//SaveRegistration(domainName, lowestLatencyIpAddress.Ipv4+":"+proxyPort) //SaveRegistration(domainName, lowestLatencyIpAddress.Ipv4+":"+proxyPort)
} }
// updating with the current proxy address // updating with the current proxy address
ProxyIpAddr.Ipv4 = lowestLatencyIpAddress.Ipv4 ProxyIpAddr.Ipv4 = lowestLatencyIpAddress.Ipv4
ProxyIpAddr.ServerPort = proxyPort ProxyIpAddr.ServerPort = proxyPort
ProxyIpAddr.Name = config.MachineName ProxyIpAddr.Name = config.MachineName
ProxyIpAddr.NAT = "False" ProxyIpAddr.NAT = "False"
ProxyIpAddr.EscapeImplementation = "FRP" ProxyIpAddr.EscapeImplementation = "FRP"
//ProxyIpAddr.CustomInformationKey = p2p.GenerateHashSHA256(config.IPTableKey) //ProxyIpAddr.CustomInformationKey = p2p.GenerateHashSHA256(config.IPTableKey)
} else { } else {
return "", "", errors.New("proxy IP not found") return "", "", errors.New("proxy IP not found")
} }
return ProxyIpAddr.Ipv4 + ":" + ProxyIpAddr.ServerPort, ProxyIpAddr.ServerPort, nil return ProxyIpAddr.Ipv4 + ":" + ProxyIpAddr.ServerPort, ProxyIpAddr.ServerPort, nil
} }