1
0

wrappers.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. "net/http"
  19. "strconv"
  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. // Update uptime monitor targets after rules updated
  91. // See https://github.com/tobychui/zoraxy/issues/77
  92. func UpdateUptimeMonitorTargets() {
  93. if uptimeMonitor != nil {
  94. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  95. go func() {
  96. uptimeMonitor.ExecuteUptimeCheck()
  97. }()
  98. SystemWideLogger.PrintAndLog("Uptime", "Uptime monitor config updated", nil)
  99. }
  100. }
  101. // Generate uptime monitor targets from reverse proxy rules
  102. func GetUptimeTargetsFromReverseProxyRules(dp *dynamicproxy.Router) []*uptime.Target {
  103. hosts := dp.GetProxyEndpointsAsMap()
  104. UptimeTargets := []*uptime.Target{}
  105. for subd, target := range hosts {
  106. url := "http://" + target.Domain
  107. protocol := "http"
  108. if target.RequireTLS {
  109. url = "https://" + target.Domain
  110. protocol = "https"
  111. }
  112. UptimeTargets = append(UptimeTargets, &uptime.Target{
  113. ID: subd,
  114. Name: subd,
  115. URL: url,
  116. Protocol: protocol,
  117. })
  118. }
  119. return UptimeTargets
  120. }
  121. // Handle rendering up time monitor data
  122. func HandleUptimeMonitorListing(w http.ResponseWriter, r *http.Request) {
  123. if uptimeMonitor != nil {
  124. uptimeMonitor.HandleUptimeLogRead(w, r)
  125. } else {
  126. http.Error(w, "500 - Internal Server Error", http.StatusInternalServerError)
  127. return
  128. }
  129. }
  130. /*
  131. Static Web Server
  132. */
  133. // Handle port change, if root router is using internal static web server
  134. // update the root router as well
  135. func HandleStaticWebServerPortChange(w http.ResponseWriter, r *http.Request) {
  136. newPort, err := utils.PostInt(r, "port")
  137. if err != nil {
  138. utils.SendErrorResponse(w, "invalid port number given")
  139. return
  140. }
  141. if dynamicProxyRouter.Root.DefaultSiteOption == dynamicproxy.DefaultSite_InternalStaticWebServer {
  142. //Update the root site as well
  143. newDraftingRoot := dynamicProxyRouter.Root.Clone()
  144. newDraftingRoot.Domain = "127.0.0.1:" + strconv.Itoa(newPort)
  145. activatedNewRoot, err := dynamicProxyRouter.PrepareProxyRoute(newDraftingRoot)
  146. if err != nil {
  147. utils.SendErrorResponse(w, "unable to update root routing rule")
  148. return
  149. }
  150. //Replace the root
  151. dynamicProxyRouter.Root = activatedNewRoot
  152. SaveReverseProxyConfig(newDraftingRoot)
  153. }
  154. err = staticWebServer.ChangePort(strconv.Itoa(newPort))
  155. if err != nil {
  156. utils.SendErrorResponse(w, err.Error())
  157. return
  158. }
  159. utils.SendOK(w)
  160. }
  161. /*
  162. mDNS Scanning
  163. */
  164. // Handle listing current registered mdns nodes
  165. func HandleMdnsListing(w http.ResponseWriter, r *http.Request) {
  166. if mdnsScanner == nil {
  167. utils.SendErrorResponse(w, "mDNS scanner is disabled on this host")
  168. return
  169. }
  170. js, _ := json.Marshal(previousmdnsScanResults)
  171. utils.SendJSONResponse(w, string(js))
  172. }
  173. func HandleMdnsScanning(w http.ResponseWriter, r *http.Request) {
  174. if mdnsScanner == nil {
  175. utils.SendErrorResponse(w, "mDNS scanner is disabled on this host")
  176. return
  177. }
  178. domain, err := utils.PostPara(r, "domain")
  179. var hosts []*mdns.NetworkHost
  180. if err != nil {
  181. //Search for arozos node
  182. hosts = mdnsScanner.Scan(30, "")
  183. previousmdnsScanResults = hosts
  184. } else {
  185. //Search for other nodes
  186. hosts = mdnsScanner.Scan(30, domain)
  187. }
  188. js, _ := json.Marshal(hosts)
  189. utils.SendJSONResponse(w, string(js))
  190. }
  191. // handle ip scanning
  192. func HandleIpScan(w http.ResponseWriter, r *http.Request) {
  193. cidr, err := utils.PostPara(r, "cidr")
  194. if err != nil {
  195. //Ip range mode
  196. start, err := utils.PostPara(r, "start")
  197. if err != nil {
  198. utils.SendErrorResponse(w, "missing start ip")
  199. return
  200. }
  201. end, err := utils.PostPara(r, "end")
  202. if err != nil {
  203. utils.SendErrorResponse(w, "missing end ip")
  204. return
  205. }
  206. discoveredHosts, err := ipscan.ScanIpRange(start, end)
  207. if err != nil {
  208. utils.SendErrorResponse(w, err.Error())
  209. return
  210. }
  211. js, _ := json.Marshal(discoveredHosts)
  212. utils.SendJSONResponse(w, string(js))
  213. } else {
  214. //CIDR mode
  215. discoveredHosts, err := ipscan.ScanCIDRRange(cidr)
  216. if err != nil {
  217. utils.SendErrorResponse(w, err.Error())
  218. return
  219. }
  220. js, _ := json.Marshal(discoveredHosts)
  221. utils.SendJSONResponse(w, string(js))
  222. }
  223. }
  224. /*
  225. WAKE ON LAN
  226. Handle wake on LAN
  227. Support following methods
  228. /?set=xxx&name=xxx Record a new MAC address into the database
  229. /?wake=xxx Wake a server given its MAC address
  230. /?del=xxx Delete a server given its MAC address
  231. / Default: list all recorded WoL MAC address
  232. */
  233. func HandleWakeOnLan(w http.ResponseWriter, r *http.Request) {
  234. set, _ := utils.PostPara(r, "set")
  235. del, _ := utils.PostPara(r, "del")
  236. wake, _ := utils.PostPara(r, "wake")
  237. if set != "" {
  238. //Get the name of the describing server
  239. servername, err := utils.PostPara(r, "name")
  240. if err != nil {
  241. utils.SendErrorResponse(w, "invalid server name given")
  242. return
  243. }
  244. //Check if the given mac address is a valid mac address
  245. set = strings.TrimSpace(set)
  246. if !wakeonlan.IsValidMacAddress(set) {
  247. utils.SendErrorResponse(w, "invalid mac address given")
  248. return
  249. }
  250. //Store this into the database
  251. sysdb.Write("wolmac", set, servername)
  252. utils.SendOK(w)
  253. } else if wake != "" {
  254. //Wake the target up by MAC address
  255. if !wakeonlan.IsValidMacAddress(wake) {
  256. utils.SendErrorResponse(w, "invalid mac address given")
  257. return
  258. }
  259. SystemWideLogger.PrintAndLog("WoL", "Sending Wake on LAN magic packet to "+wake, nil)
  260. err := wakeonlan.WakeTarget(wake)
  261. if err != nil {
  262. utils.SendErrorResponse(w, err.Error())
  263. return
  264. }
  265. utils.SendOK(w)
  266. } else if del != "" {
  267. if !wakeonlan.IsValidMacAddress(del) {
  268. utils.SendErrorResponse(w, "invalid mac address given")
  269. return
  270. }
  271. sysdb.Delete("wolmac", del)
  272. utils.SendOK(w)
  273. } else {
  274. //List all the saved WoL MAC Address
  275. entries, err := sysdb.ListTable("wolmac")
  276. if err != nil {
  277. utils.SendErrorResponse(w, "unknown error occured")
  278. return
  279. }
  280. type MacAddrRecord struct {
  281. ServerName string
  282. MacAddr string
  283. }
  284. results := []*MacAddrRecord{}
  285. for _, keypairs := range entries {
  286. macAddr := string(keypairs[0])
  287. serverName := ""
  288. json.Unmarshal(keypairs[1], &serverName)
  289. results = append(results, &MacAddrRecord{
  290. ServerName: serverName,
  291. MacAddr: macAddr,
  292. })
  293. }
  294. js, _ := json.Marshal(results)
  295. utils.SendJSONResponse(w, string(js))
  296. }
  297. }
  298. /*
  299. Zoraxy Host Info
  300. */
  301. func HandleZoraxyInfo(w http.ResponseWriter, r *http.Request) {
  302. type ZoraxyInfo struct {
  303. Version string
  304. NodeUUID string
  305. Development bool
  306. BootTime int64
  307. EnableSshLoopback bool
  308. ZerotierConnected bool
  309. }
  310. info := ZoraxyInfo{
  311. Version: version,
  312. NodeUUID: nodeUUID,
  313. Development: development,
  314. BootTime: bootTime,
  315. EnableSshLoopback: *allowSshLoopback,
  316. ZerotierConnected: ganManager.ControllerID != "",
  317. }
  318. js, _ := json.MarshalIndent(info, "", " ")
  319. utils.SendJSONResponse(w, string(js))
  320. }
  321. func HandleGeoIpLookup(w http.ResponseWriter, r *http.Request) {
  322. ip, err := utils.GetPara(r, "ip")
  323. if err != nil {
  324. utils.SendErrorResponse(w, "ip not given")
  325. return
  326. }
  327. cc, err := geodbStore.ResolveCountryCodeFromIP(ip)
  328. if err != nil {
  329. utils.SendErrorResponse(w, err.Error())
  330. return
  331. }
  332. js, _ := json.Marshal(cc)
  333. utils.SendJSONResponse(w, string(js))
  334. }