utils.go 1.2 KB

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