utils.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package sshprox
  2. import (
  3. "fmt"
  4. "net"
  5. "net/url"
  6. "runtime"
  7. "strings"
  8. "time"
  9. )
  10. //Rewrite url based on proxy root
  11. func RewriteURL(rooturl string, requestURL string) (*url.URL, error) {
  12. rewrittenURL := strings.TrimPrefix(requestURL, rooturl)
  13. return url.Parse(rewrittenURL)
  14. }
  15. //Check if the current platform support web.ssh function
  16. func IsWebSSHSupported() bool {
  17. //Check if the binary exists in system/gotty/
  18. binary := "gotty_" + runtime.GOOS + "_" + runtime.GOARCH
  19. if runtime.GOOS == "windows" {
  20. binary = binary + ".exe"
  21. }
  22. //Check if the target gotty terminal exists
  23. f, err := gotty.Open("gotty/" + binary)
  24. if err != nil {
  25. return false
  26. }
  27. f.Close()
  28. return true
  29. }
  30. //Check if a given domain and port is a valid ssh server
  31. func IsSSHConnectable(ipOrDomain string, port int) bool {
  32. timeout := time.Second * 3
  33. conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ipOrDomain, port), timeout)
  34. if err != nil {
  35. return false
  36. }
  37. defer conn.Close()
  38. // Send an SSH version identification string to the server to check if it's SSH
  39. _, err = conn.Write([]byte("SSH-2.0-Go\r\n"))
  40. if err != nil {
  41. return false
  42. }
  43. // Wait for a response from the server
  44. buf := make([]byte, 1024)
  45. _, err = conn.Read(buf)
  46. if err != nil {
  47. return false
  48. }
  49. // Check if the response starts with "SSH-2.0"
  50. return string(buf[:7]) == "SSH-2.0"
  51. }
  52. //Check if the port is used by other process or application
  53. func isPortInUse(port int) bool {
  54. address := fmt.Sprintf(":%d", port)
  55. listener, err := net.Listen("tcp", address)
  56. if err != nil {
  57. return true
  58. }
  59. listener.Close()
  60. return false
  61. }