wrappers.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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/ipscan"
  25. "imuslab.com/zoraxy/mod/mdns"
  26. "imuslab.com/zoraxy/mod/uptime"
  27. "imuslab.com/zoraxy/mod/utils"
  28. "imuslab.com/zoraxy/mod/wakeonlan"
  29. )
  30. /*
  31. Proxy Utils
  32. */
  33. //Check if site support TLS
  34. func HandleCheckSiteSupportTLS(w http.ResponseWriter, r *http.Request) {
  35. targetURL, err := utils.PostPara(r, "url")
  36. if err != nil {
  37. utils.SendErrorResponse(w, "invalid url given")
  38. return
  39. }
  40. httpsUrl := fmt.Sprintf("https://%s", targetURL)
  41. httpUrl := fmt.Sprintf("http://%s", targetURL)
  42. client := http.Client{Timeout: 5 * time.Second}
  43. resp, err := client.Head(httpsUrl)
  44. if err == nil && resp.StatusCode == http.StatusOK {
  45. js, _ := json.Marshal("https")
  46. utils.SendJSONResponse(w, string(js))
  47. return
  48. }
  49. resp, err = client.Head(httpUrl)
  50. if err == nil && resp.StatusCode == http.StatusOK {
  51. js, _ := json.Marshal("http")
  52. utils.SendJSONResponse(w, string(js))
  53. return
  54. }
  55. utils.SendErrorResponse(w, "invalid url given")
  56. }
  57. /*
  58. Statistic Summary
  59. */
  60. // Handle conversion of statistic daily summary to country summary
  61. func HandleCountryDistrSummary(w http.ResponseWriter, r *http.Request) {
  62. requestClientCountry := map[string]int{}
  63. statisticCollector.DailySummary.RequestClientIp.Range(func(key, value interface{}) bool {
  64. //Get this client country of original
  65. clientIp := key.(string)
  66. //requestCount := value.(int)
  67. ci, err := geodbStore.ResolveCountryCodeFromIP(clientIp)
  68. if err != nil {
  69. return true
  70. }
  71. isoCode := ci.CountryIsoCode
  72. if isoCode == "" {
  73. //local or reserved addr
  74. isoCode = "local"
  75. }
  76. uc, ok := requestClientCountry[isoCode]
  77. if !ok {
  78. //Create the counter
  79. requestClientCountry[isoCode] = 1
  80. } else {
  81. requestClientCountry[isoCode] = uc + 1
  82. }
  83. return true
  84. })
  85. js, _ := json.Marshal(requestClientCountry)
  86. utils.SendJSONResponse(w, string(js))
  87. }
  88. /*
  89. Up Time Monitor
  90. */
  91. // Update uptime monitor targets after rules updated
  92. // See https://github.com/tobychui/zoraxy/issues/77
  93. func UpdateUptimeMonitorTargets() {
  94. if uptimeMonitor != nil {
  95. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  96. go func() {
  97. uptimeMonitor.ExecuteUptimeCheck()
  98. }()
  99. SystemWideLogger.PrintAndLog("Uptime", "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. for _, origin := range target.ActiveOrigins {
  108. url := "http://" + origin.OriginIpOrDomain
  109. protocol := "http"
  110. if origin.RequireTLS {
  111. url = "https://" + origin.OriginIpOrDomain
  112. protocol = "https"
  113. }
  114. //Add the root url
  115. UptimeTargets = append(UptimeTargets, &uptime.Target{
  116. ID: hostid,
  117. Name: hostid,
  118. URL: url,
  119. Protocol: protocol,
  120. ProxyType: uptime.ProxyType_Host,
  121. })
  122. //Add each virtual directory into the list
  123. for _, vdir := range target.VirtualDirectories {
  124. url := "http://" + vdir.Domain
  125. protocol := "http"
  126. if origin.RequireTLS {
  127. url = "https://" + vdir.Domain
  128. protocol = "https"
  129. }
  130. //Add the root url
  131. UptimeTargets = append(UptimeTargets, &uptime.Target{
  132. ID: hostid + vdir.MatchingPath,
  133. Name: hostid + vdir.MatchingPath,
  134. URL: url,
  135. Protocol: protocol,
  136. ProxyType: uptime.ProxyType_Vdir,
  137. })
  138. }
  139. }
  140. }
  141. return UptimeTargets
  142. }
  143. // Handle rendering up time monitor data
  144. func HandleUptimeMonitorListing(w http.ResponseWriter, r *http.Request) {
  145. if uptimeMonitor != nil {
  146. uptimeMonitor.HandleUptimeLogRead(w, r)
  147. } else {
  148. http.Error(w, "500 - Internal Server Error", http.StatusInternalServerError)
  149. return
  150. }
  151. }
  152. /*
  153. Static Web Server
  154. */
  155. // Handle port change, if root router is using internal static web server
  156. // update the root router as well
  157. func HandleStaticWebServerPortChange(w http.ResponseWriter, r *http.Request) {
  158. newPort, err := utils.PostInt(r, "port")
  159. if err != nil {
  160. utils.SendErrorResponse(w, "invalid port number given")
  161. return
  162. }
  163. if dynamicProxyRouter.Root.DefaultSiteOption == dynamicproxy.DefaultSite_InternalStaticWebServer {
  164. //Update the root site as well
  165. newDraftingRoot := dynamicProxyRouter.Root.Clone()
  166. newDraftingRoot.ActiveOrigins = []*loadbalance.Upstream{
  167. {
  168. OriginIpOrDomain: "127.0.0.1:" + strconv.Itoa(newPort),
  169. RequireTLS: false,
  170. SkipCertValidations: false,
  171. SkipWebSocketOriginCheck: true,
  172. Weight: 0,
  173. },
  174. }
  175. activatedNewRoot, err := dynamicProxyRouter.PrepareProxyRoute(newDraftingRoot)
  176. if err != nil {
  177. utils.SendErrorResponse(w, "unable to update root routing rule")
  178. return
  179. }
  180. //Replace the root
  181. dynamicProxyRouter.Root = activatedNewRoot
  182. SaveReverseProxyConfig(newDraftingRoot)
  183. }
  184. err = staticWebServer.ChangePort(strconv.Itoa(newPort))
  185. if err != nil {
  186. utils.SendErrorResponse(w, err.Error())
  187. return
  188. }
  189. utils.SendOK(w)
  190. }
  191. /*
  192. mDNS Scanning
  193. */
  194. // Handle listing current registered mdns nodes
  195. func HandleMdnsListing(w http.ResponseWriter, r *http.Request) {
  196. if mdnsScanner == nil {
  197. utils.SendErrorResponse(w, "mDNS scanner is disabled on this host")
  198. return
  199. }
  200. js, _ := json.Marshal(previousmdnsScanResults)
  201. utils.SendJSONResponse(w, string(js))
  202. }
  203. func HandleMdnsScanning(w http.ResponseWriter, r *http.Request) {
  204. if mdnsScanner == nil {
  205. utils.SendErrorResponse(w, "mDNS scanner is disabled on this host")
  206. return
  207. }
  208. domain, err := utils.PostPara(r, "domain")
  209. var hosts []*mdns.NetworkHost
  210. if err != nil {
  211. //Search for arozos node
  212. hosts = mdnsScanner.Scan(30, "")
  213. previousmdnsScanResults = hosts
  214. } else {
  215. //Search for other nodes
  216. hosts = mdnsScanner.Scan(30, domain)
  217. }
  218. js, _ := json.Marshal(hosts)
  219. utils.SendJSONResponse(w, string(js))
  220. }
  221. // handle ip scanning
  222. func HandleIpScan(w http.ResponseWriter, r *http.Request) {
  223. cidr, err := utils.PostPara(r, "cidr")
  224. if err != nil {
  225. //Ip range mode
  226. start, err := utils.PostPara(r, "start")
  227. if err != nil {
  228. utils.SendErrorResponse(w, "missing start ip")
  229. return
  230. }
  231. end, err := utils.PostPara(r, "end")
  232. if err != nil {
  233. utils.SendErrorResponse(w, "missing end ip")
  234. return
  235. }
  236. discoveredHosts, err := ipscan.ScanIpRange(start, end)
  237. if err != nil {
  238. utils.SendErrorResponse(w, err.Error())
  239. return
  240. }
  241. js, _ := json.Marshal(discoveredHosts)
  242. utils.SendJSONResponse(w, string(js))
  243. } else {
  244. //CIDR mode
  245. discoveredHosts, err := ipscan.ScanCIDRRange(cidr)
  246. if err != nil {
  247. utils.SendErrorResponse(w, err.Error())
  248. return
  249. }
  250. js, _ := json.Marshal(discoveredHosts)
  251. utils.SendJSONResponse(w, string(js))
  252. }
  253. }
  254. /*
  255. WAKE ON LAN
  256. Handle wake on LAN
  257. Support following methods
  258. /?set=xxx&name=xxx Record a new MAC address into the database
  259. /?wake=xxx Wake a server given its MAC address
  260. /?del=xxx Delete a server given its MAC address
  261. / Default: list all recorded WoL MAC address
  262. */
  263. func HandleWakeOnLan(w http.ResponseWriter, r *http.Request) {
  264. set, _ := utils.PostPara(r, "set")
  265. del, _ := utils.PostPara(r, "del")
  266. wake, _ := utils.PostPara(r, "wake")
  267. if set != "" {
  268. //Get the name of the describing server
  269. servername, err := utils.PostPara(r, "name")
  270. if err != nil {
  271. utils.SendErrorResponse(w, "invalid server name given")
  272. return
  273. }
  274. //Check if the given mac address is a valid mac address
  275. set = strings.TrimSpace(set)
  276. if !wakeonlan.IsValidMacAddress(set) {
  277. utils.SendErrorResponse(w, "invalid mac address given")
  278. return
  279. }
  280. //Store this into the database
  281. sysdb.Write("wolmac", set, servername)
  282. utils.SendOK(w)
  283. } else if wake != "" {
  284. //Wake the target up by MAC address
  285. if !wakeonlan.IsValidMacAddress(wake) {
  286. utils.SendErrorResponse(w, "invalid mac address given")
  287. return
  288. }
  289. SystemWideLogger.PrintAndLog("WoL", "Sending Wake on LAN magic packet to "+wake, nil)
  290. err := wakeonlan.WakeTarget(wake)
  291. if err != nil {
  292. utils.SendErrorResponse(w, err.Error())
  293. return
  294. }
  295. utils.SendOK(w)
  296. } else if del != "" {
  297. if !wakeonlan.IsValidMacAddress(del) {
  298. utils.SendErrorResponse(w, "invalid mac address given")
  299. return
  300. }
  301. sysdb.Delete("wolmac", del)
  302. utils.SendOK(w)
  303. } else {
  304. //List all the saved WoL MAC Address
  305. entries, err := sysdb.ListTable("wolmac")
  306. if err != nil {
  307. utils.SendErrorResponse(w, "unknown error occured")
  308. return
  309. }
  310. type MacAddrRecord struct {
  311. ServerName string
  312. MacAddr string
  313. }
  314. results := []*MacAddrRecord{}
  315. for _, keypairs := range entries {
  316. macAddr := string(keypairs[0])
  317. serverName := ""
  318. json.Unmarshal(keypairs[1], &serverName)
  319. results = append(results, &MacAddrRecord{
  320. ServerName: serverName,
  321. MacAddr: macAddr,
  322. })
  323. }
  324. js, _ := json.Marshal(results)
  325. utils.SendJSONResponse(w, string(js))
  326. }
  327. }
  328. /*
  329. Zoraxy Host Info
  330. */
  331. func HandleZoraxyInfo(w http.ResponseWriter, r *http.Request) {
  332. type ZoraxyInfo struct {
  333. Version string
  334. NodeUUID string
  335. Development bool
  336. BootTime int64
  337. EnableSshLoopback bool
  338. ZerotierConnected bool
  339. }
  340. info := ZoraxyInfo{
  341. Version: version,
  342. NodeUUID: nodeUUID,
  343. Development: development,
  344. BootTime: bootTime,
  345. EnableSshLoopback: *allowSshLoopback,
  346. ZerotierConnected: ganManager.ControllerID != "",
  347. }
  348. js, _ := json.MarshalIndent(info, "", " ")
  349. utils.SendJSONResponse(w, string(js))
  350. }
  351. func HandleGeoIpLookup(w http.ResponseWriter, r *http.Request) {
  352. ip, err := utils.GetPara(r, "ip")
  353. if err != nil {
  354. utils.SendErrorResponse(w, "ip not given")
  355. return
  356. }
  357. cc, err := geodbStore.ResolveCountryCodeFromIP(ip)
  358. if err != nil {
  359. utils.SendErrorResponse(w, err.Error())
  360. return
  361. }
  362. js, _ := json.Marshal(cc)
  363. utils.SendJSONResponse(w, string(js))
  364. }