wrappers.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package main
  2. /*
  3. Wrappers.go
  4. This script provide wrapping functions
  5. for modules that do not provide
  6. handler interface within the modules
  7. --- NOTES ---
  8. If your module have more than one layer
  9. or require state keeping, please move
  10. the abstraction up one layer into
  11. your own module. Do not keep state on
  12. the global scope other than single
  13. Manager instance
  14. */
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "log"
  19. "net/http"
  20. "strings"
  21. "time"
  22. "imuslab.com/zoraxy/mod/dynamicproxy"
  23. "imuslab.com/zoraxy/mod/ipscan"
  24. "imuslab.com/zoraxy/mod/mdns"
  25. "imuslab.com/zoraxy/mod/uptime"
  26. "imuslab.com/zoraxy/mod/utils"
  27. "imuslab.com/zoraxy/mod/wakeonlan"
  28. )
  29. /*
  30. Proxy Utils
  31. */
  32. //Check if site support TLS
  33. func HandleCheckSiteSupportTLS(w http.ResponseWriter, r *http.Request) {
  34. targetURL, err := utils.PostPara(r, "url")
  35. if err != nil {
  36. utils.SendErrorResponse(w, "invalid url given")
  37. return
  38. }
  39. httpsUrl := fmt.Sprintf("https://%s", targetURL)
  40. httpUrl := fmt.Sprintf("http://%s", targetURL)
  41. client := http.Client{Timeout: 5 * time.Second}
  42. resp, err := client.Head(httpsUrl)
  43. if err == nil && resp.StatusCode == http.StatusOK {
  44. js, _ := json.Marshal("https")
  45. utils.SendJSONResponse(w, string(js))
  46. return
  47. }
  48. resp, err = client.Head(httpUrl)
  49. if err == nil && resp.StatusCode == http.StatusOK {
  50. js, _ := json.Marshal("http")
  51. utils.SendJSONResponse(w, string(js))
  52. return
  53. }
  54. utils.SendErrorResponse(w, "invalid url given")
  55. }
  56. /*
  57. Statistic Summary
  58. */
  59. // Handle conversion of statistic daily summary to country summary
  60. func HandleCountryDistrSummary(w http.ResponseWriter, r *http.Request) {
  61. requestClientCountry := map[string]int{}
  62. statisticCollector.DailySummary.RequestClientIp.Range(func(key, value interface{}) bool {
  63. //Get this client country of original
  64. clientIp := key.(string)
  65. //requestCount := value.(int)
  66. ci, err := geodbStore.ResolveCountryCodeFromIP(clientIp)
  67. if err != nil {
  68. return true
  69. }
  70. isoCode := ci.CountryIsoCode
  71. if isoCode == "" {
  72. //local or reserved addr
  73. isoCode = "local"
  74. }
  75. uc, ok := requestClientCountry[isoCode]
  76. if !ok {
  77. //Create the counter
  78. requestClientCountry[isoCode] = 1
  79. } else {
  80. requestClientCountry[isoCode] = uc + 1
  81. }
  82. return true
  83. })
  84. js, _ := json.Marshal(requestClientCountry)
  85. utils.SendJSONResponse(w, string(js))
  86. }
  87. /*
  88. Up Time Monitor
  89. */
  90. //Generate uptime monitor targets from reverse proxy rules
  91. func GetUptimeTargetsFromReverseProxyRules(dp *dynamicproxy.Router) []*uptime.Target {
  92. subds := dp.GetSDProxyEndpointsAsMap()
  93. vdirs := dp.GetVDProxyEndpointsAsMap()
  94. UptimeTargets := []*uptime.Target{}
  95. for subd, target := range subds {
  96. url := "http://" + target.Domain
  97. protocol := "http"
  98. if target.RequireTLS {
  99. url = "https://" + target.Domain
  100. protocol = "https"
  101. }
  102. UptimeTargets = append(UptimeTargets, &uptime.Target{
  103. ID: subd,
  104. Name: subd,
  105. URL: url,
  106. Protocol: protocol,
  107. })
  108. }
  109. for vdir, target := range vdirs {
  110. url := "http://" + target.Domain
  111. protocol := "http"
  112. if target.RequireTLS {
  113. url = "https://" + target.Domain
  114. protocol = "https"
  115. }
  116. UptimeTargets = append(UptimeTargets, &uptime.Target{
  117. ID: vdir,
  118. Name: "*" + vdir,
  119. URL: url,
  120. Protocol: protocol,
  121. })
  122. }
  123. return UptimeTargets
  124. }
  125. // Handle rendering up time monitor data
  126. func HandleUptimeMonitorListing(w http.ResponseWriter, r *http.Request) {
  127. if uptimeMonitor != nil {
  128. uptimeMonitor.HandleUptimeLogRead(w, r)
  129. } else {
  130. http.Error(w, "500 - Internal Server Error", http.StatusInternalServerError)
  131. return
  132. }
  133. }
  134. // Handle listing current registered mdns nodes
  135. func HandleMdnsListing(w http.ResponseWriter, r *http.Request) {
  136. js, _ := json.Marshal(previousmdnsScanResults)
  137. utils.SendJSONResponse(w, string(js))
  138. }
  139. func HandleMdnsScanning(w http.ResponseWriter, r *http.Request) {
  140. domain, err := utils.PostPara(r, "domain")
  141. var hosts []*mdns.NetworkHost
  142. if err != nil {
  143. //Search for arozos node
  144. hosts = mdnsScanner.Scan(30, "")
  145. previousmdnsScanResults = hosts
  146. } else {
  147. //Search for other nodes
  148. hosts = mdnsScanner.Scan(30, domain)
  149. }
  150. js, _ := json.Marshal(hosts)
  151. utils.SendJSONResponse(w, string(js))
  152. }
  153. // handle ip scanning
  154. func HandleIpScan(w http.ResponseWriter, r *http.Request) {
  155. cidr, err := utils.PostPara(r, "cidr")
  156. if err != nil {
  157. //Ip range mode
  158. start, err := utils.PostPara(r, "start")
  159. if err != nil {
  160. utils.SendErrorResponse(w, "missing start ip")
  161. return
  162. }
  163. end, err := utils.PostPara(r, "end")
  164. if err != nil {
  165. utils.SendErrorResponse(w, "missing end ip")
  166. return
  167. }
  168. discoveredHosts, err := ipscan.ScanIpRange(start, end)
  169. if err != nil {
  170. utils.SendErrorResponse(w, err.Error())
  171. return
  172. }
  173. js, _ := json.Marshal(discoveredHosts)
  174. utils.SendJSONResponse(w, string(js))
  175. } else {
  176. //CIDR mode
  177. discoveredHosts, err := ipscan.ScanCIDRRange(cidr)
  178. if err != nil {
  179. utils.SendErrorResponse(w, err.Error())
  180. return
  181. }
  182. js, _ := json.Marshal(discoveredHosts)
  183. utils.SendJSONResponse(w, string(js))
  184. }
  185. }
  186. /*
  187. WAKE ON LAN
  188. Handle wake on LAN
  189. Support following methods
  190. /?set=xxx&name=xxx Record a new MAC address into the database
  191. /?wake=xxx Wake a server given its MAC address
  192. /?del=xxx Delete a server given its MAC address
  193. / Default: list all recorded WoL MAC address
  194. */
  195. func HandleWakeOnLan(w http.ResponseWriter, r *http.Request) {
  196. set, _ := utils.PostPara(r, "set")
  197. del, _ := utils.PostPara(r, "del")
  198. wake, _ := utils.PostPara(r, "wake")
  199. if set != "" {
  200. //Get the name of the describing server
  201. servername, err := utils.PostPara(r, "name")
  202. if err != nil {
  203. utils.SendErrorResponse(w, "invalid server name given")
  204. return
  205. }
  206. //Check if the given mac address is a valid mac address
  207. set = strings.TrimSpace(set)
  208. if !wakeonlan.IsValidMacAddress(set) {
  209. utils.SendErrorResponse(w, "invalid mac address given")
  210. return
  211. }
  212. //Store this into the database
  213. sysdb.Write("wolmac", set, servername)
  214. utils.SendOK(w)
  215. } else if wake != "" {
  216. //Wake the target up by MAC address
  217. if !wakeonlan.IsValidMacAddress(wake) {
  218. utils.SendErrorResponse(w, "invalid mac address given")
  219. return
  220. }
  221. log.Println("[WoL] Sending Wake on LAN magic packet to " + wake)
  222. err := wakeonlan.WakeTarget(wake)
  223. if err != nil {
  224. utils.SendErrorResponse(w, err.Error())
  225. return
  226. }
  227. utils.SendOK(w)
  228. } else if del != "" {
  229. if !wakeonlan.IsValidMacAddress(del) {
  230. utils.SendErrorResponse(w, "invalid mac address given")
  231. return
  232. }
  233. sysdb.Delete("wolmac", del)
  234. utils.SendOK(w)
  235. } else {
  236. //List all the saved WoL MAC Address
  237. entries, err := sysdb.ListTable("wolmac")
  238. if err != nil {
  239. utils.SendErrorResponse(w, "unknown error occured")
  240. return
  241. }
  242. type MacAddrRecord struct {
  243. ServerName string
  244. MacAddr string
  245. }
  246. results := []*MacAddrRecord{}
  247. for _, keypairs := range entries {
  248. macAddr := string(keypairs[0])
  249. serverName := ""
  250. json.Unmarshal(keypairs[1], &serverName)
  251. results = append(results, &MacAddrRecord{
  252. ServerName: serverName,
  253. MacAddr: macAddr,
  254. })
  255. }
  256. js, _ := json.Marshal(results)
  257. utils.SendJSONResponse(w, string(js))
  258. }
  259. }
  260. /*
  261. Zoraxy Host Info
  262. */
  263. func HandleZoraxyInfo(w http.ResponseWriter, r *http.Request) {
  264. type ZoraxyInfo struct {
  265. Version string
  266. NodeUUID string
  267. Development bool
  268. BootTime int64
  269. EnableSshLoopback bool
  270. ZerotierConnected bool
  271. }
  272. info := ZoraxyInfo{
  273. Version: version,
  274. NodeUUID: nodeUUID,
  275. Development: development,
  276. BootTime: bootTime,
  277. EnableSshLoopback: *allowSshLoopback,
  278. ZerotierConnected: ganManager.ControllerID != "",
  279. }
  280. js, _ := json.MarshalIndent(info, "", " ")
  281. utils.SendJSONResponse(w, string(js))
  282. }