webserver.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package kyoketsu
  2. import (
  3. "embed"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "io"
  8. "log"
  9. "net/http"
  10. "path"
  11. "strings"
  12. )
  13. type ScanRequest struct {
  14. IpAddress string `json:"ip_address"`
  15. FqdnPattern string `json:"fqdn_pattern"`
  16. }
  17. // Holding all static web server resources
  18. //
  19. //go:embed html/bootstrap-5.0.2-dist/js/* html/bootstrap-5.0.2-dist/css/* html/* html/templates/*
  20. var content embed.FS
  21. /*
  22. Run a new webserver
  23. :param port: port number to run the webserver on
  24. */
  25. func RunHttpServer(port int, dbhook TopologyDatabaseIO, portmap []int) {
  26. assets := &AssetHandler{Root: content, RelPath: "static", EmbedRoot: "html"}
  27. tmpl, err := template.ParseFS(content, "html/templates/*.html")
  28. if err != nil {
  29. log.Fatal(err)
  30. }
  31. iptable, err := template.ParseFS(content, "html/templates/ip_table.html")
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. htmlHndl := &HtmlHandler{Home: tmpl, TableEntry: iptable, DbHook: dbhook}
  36. execHndl := &ExecutionHandler{DbHook: dbhook, PortMap: portmap, TableEntry: iptable}
  37. http.Handle("/static/", assets)
  38. http.Handle("/home", htmlHndl)
  39. http.Handle("/subnets", htmlHndl)
  40. http.Handle("/excludefqdn", htmlHndl)
  41. http.Handle("/refresh", execHndl)
  42. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
  43. }
  44. type ExecutionHandler struct {
  45. DbHook TopologyDatabaseIO
  46. TableEntry *template.Template
  47. PortMap []int
  48. }
  49. func (e *ExecutionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  50. var input ScanRequest
  51. b, err := io.ReadAll(r.Body)
  52. defer r.Body.Close()
  53. if err != nil {
  54. fmt.Fprintf(w, "There was an error processing your request: %s", err)
  55. return
  56. }
  57. err = json.Unmarshal(b, &input)
  58. if err != nil {
  59. fmt.Fprintf(w, "There was an error processing your request: %s", err)
  60. return
  61. }
  62. subnetMap, err := GetNetworkAddresses(input.IpAddress)
  63. if err != nil {
  64. fmt.Fprintf(w, "There was an error processing your request: %s", err)
  65. }
  66. scanned := make(chan Host)
  67. go func(wr http.ResponseWriter, templ *template.Template) {
  68. for x := range scanned {
  69. if len(x.ListeningPorts) > 0 {
  70. err := templ.Execute(wr, x)
  71. if err != nil {
  72. fmt.Println(err, x)
  73. }
  74. host, err := e.DbHook.GetByIP(x.IpAddress)
  75. if err != nil {
  76. if err != ErrNotExists {
  77. log.Fatal(err, " Couldnt access the database. Fatal error.\n")
  78. }
  79. _, err = e.DbHook.Create(x)
  80. if err != nil {
  81. log.Fatal(err, " Fatal error trying to read the database.\n")
  82. }
  83. continue
  84. }
  85. _, err = e.DbHook.Update(host.Id, x)
  86. if err != nil {
  87. log.Fatal(err, " fatal error when updating a record.\n")
  88. }
  89. }
  90. }
  91. }(w, e.TableEntry)
  92. NetSweep(subnetMap.Ipv4s, subnetMap.Mask, RetrieveScanDirectives(), scanned)
  93. }
  94. // handlers //
  95. type HtmlHandler struct {
  96. Home *template.Template // pointer to the HTML homepage
  97. TableEntry *template.Template // pointer to the table entry html template
  98. DbHook TopologyDatabaseIO
  99. }
  100. func (h *HtmlHandler) subnetQueryHandler(w http.ResponseWriter, r *http.Request) {
  101. var req ScanRequest
  102. b, err := io.ReadAll(r.Body)
  103. defer r.Body.Close()
  104. if err != nil {
  105. fmt.Fprintf(w, "There was an error reading the input: %s", err)
  106. return
  107. }
  108. err = json.Unmarshal(b, &req)
  109. if err != nil {
  110. fmt.Fprintf(w, "There was an error reading the input: %s", err)
  111. return
  112. }
  113. data, err := h.DbHook.GetByNetwork(req.IpAddress)
  114. if err != nil {
  115. fmt.Fprintf(w, "There was an error reading from the database: %s", err)
  116. return
  117. }
  118. for _, host := range data {
  119. h.TableEntry.Execute(w, host)
  120. }
  121. }
  122. func (h *HtmlHandler) fqdnQueryHandler(w http.ResponseWriter, r *http.Request) {
  123. var req ScanRequest
  124. b, err := io.ReadAll(r.Body)
  125. defer r.Body.Close()
  126. if err != nil {
  127. fmt.Fprintf(w, "There was an error reading the input: %s", err)
  128. return
  129. }
  130. err = json.Unmarshal(b, &req)
  131. if err != nil {
  132. fmt.Fprintf(w, "There was an error reading the input: %s", err)
  133. return
  134. }
  135. dnsList := strings.Split(req.FqdnPattern, ",")
  136. data, err := h.DbHook.FilterDnsPattern(dnsList)
  137. if err != nil {
  138. fmt.Fprintf(w, "There was an error reading from the database: %s", err)
  139. return
  140. }
  141. for _, host := range data {
  142. h.TableEntry.Execute(w, host)
  143. }
  144. }
  145. /*
  146. Handler function for HTML serving
  147. :param w: http.ResponseWriter interface for sending data back
  148. :param r: pointer to the http.Request coming in
  149. */
  150. func (h *HtmlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  151. if r.RequestURI == "/home" {
  152. data, err := h.DbHook.All()
  153. if err != nil {
  154. fmt.Fprintf(w, "You have made it to the kyoketsu web server!\nThere was an error getting the db table, though.\n%s", err)
  155. }
  156. h.Home.Execute(w, data)
  157. return
  158. }
  159. splitpath := strings.Split(r.RequestURI, "/")
  160. if len(splitpath) <= 1 {
  161. w.Header().Add("Location", "/home")
  162. return
  163. }
  164. switch r.RequestURI {
  165. case "/subnets":
  166. h.subnetQueryHandler(w, r)
  167. case "/excludefqdn":
  168. h.fqdnQueryHandler(w, r)
  169. }
  170. }
  171. type AssetHandler struct {
  172. Root embed.FS // Should be able to use anything that implements the fs.FS interface for serving asset files
  173. EmbedRoot string // This is the root of the embeded file system
  174. RelPath string // The path that will be used for the handler, relative to the root of the webserver (/static, /assets, etc)
  175. }
  176. /*
  177. Handler function to serve out asset files (HTMX, bootstrap, pngs etc)
  178. :param w: http.ResponseWriter interface for sending data back to the caller
  179. :param r: pointer to an http.Request
  180. */
  181. func (a *AssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  182. var uripath string // the path from the request
  183. var pathSp []string // the path from the request split, so that we can point the request path to the embedded fs
  184. var assetPath []string // the cleaned path for the requested asset
  185. var fname string // filename of the requested asset
  186. var ctype string
  187. var b []byte
  188. var err error
  189. uripath = strings.TrimPrefix(r.URL.Path, a.RelPath)
  190. uripath = strings.Trim(uripath, "/")
  191. pathSp = strings.Split(uripath, "/")
  192. fname = pathSp[len(pathSp)-1]
  193. assetPath = append(assetPath, a.EmbedRoot)
  194. for i := 1; i < len(pathSp); i++ {
  195. assetPath = append(assetPath, pathSp[i])
  196. }
  197. b, err = a.Root.ReadFile(path.Join(assetPath...))
  198. if err != nil {
  199. fmt.Fprintf(w, "Error occured: %s. path split: '%s'\nAsset Path: %s", err, pathSp, assetPath)
  200. }
  201. switch {
  202. case strings.Contains(fname, "css"):
  203. ctype = "text/css"
  204. case strings.Contains(fname, "js"):
  205. ctype = "text/javascript"
  206. case strings.Contains(fname, "html"):
  207. ctype = "text/html"
  208. case strings.Contains(fname, "json"):
  209. ctype = "application/json"
  210. case strings.Contains(fname, "png"):
  211. ctype = "image/png"
  212. default:
  213. ctype = "text"
  214. }
  215. w.Header().Add("Content-Type", ctype)
  216. fmt.Fprint(w, string(b))
  217. }