wrappers.go 9.6 KB

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