utils.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package sshprox
  2. import (
  3. "fmt"
  4. "net"
  5. "net/url"
  6. "strings"
  7. "time"
  8. )
  9. //Rewrite url based on proxy root
  10. func RewriteURL(rooturl string, requestURL string) (*url.URL, error) {
  11. rewrittenURL := strings.TrimPrefix(requestURL, rooturl)
  12. return url.Parse(rewrittenURL)
  13. }
  14. //Check if a given domain and port is a valid ssh server
  15. func IsSSHConnectable(ipOrDomain string, port int) bool {
  16. timeout := time.Second * 3
  17. conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ipOrDomain, port), timeout)
  18. if err != nil {
  19. return false
  20. }
  21. defer conn.Close()
  22. // Send an SSH version identification string to the server to check if it's SSH
  23. _, err = conn.Write([]byte("SSH-2.0-Go\r\n"))
  24. if err != nil {
  25. return false
  26. }
  27. // Wait for a response from the server
  28. buf := make([]byte, 1024)
  29. _, err = conn.Read(buf)
  30. if err != nil {
  31. return false
  32. }
  33. // Check if the response starts with "SSH-2.0"
  34. return string(buf[:7]) == "SSH-2.0"
  35. }
  36. //Check if the port is used by other process or application
  37. func isPortInUse(port int) bool {
  38. address := fmt.Sprintf(":%d", port)
  39. listener, err := net.Listen("tcp", address)
  40. if err != nil {
  41. return true
  42. }
  43. listener.Close()
  44. return false
  45. }