webserver.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. }
  16. // Holding all static web server resources
  17. //
  18. //go:embed html/bootstrap-5.0.2-dist/js/* html/bootstrap-5.0.2-dist/css/* html/* html/templates/* html/img/*
  19. var content embed.FS
  20. /*
  21. Run a new webserver
  22. :param port: port number to run the webserver on
  23. */
  24. func RunHttpServer(port int, dbhook TopologyDatabaseIO, portmap map[int]string) {
  25. assets := &AssetHandler{Root: content, RelPath: "static", EmbedRoot: "html"}
  26. tmpl, err := template.ParseFS(content, "html/templates/*.html")
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. iptable, err := template.ParseFS(content, "html/templates/ip_table.html")
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. htmlHndl := &HtmlHandler{Home: tmpl, DbHook: dbhook}
  35. execHndl := &ExecutionHandler{DbHook: dbhook, PortMap: portmap, TableEntry: iptable}
  36. http.Handle("/static/", assets)
  37. http.Handle("/home", htmlHndl)
  38. http.Handle("/refresh", execHndl)
  39. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
  40. }
  41. type ExecutionHandler struct {
  42. DbHook TopologyDatabaseIO
  43. TableEntry *template.Template
  44. PortMap map[int]string
  45. }
  46. func (e *ExecutionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  47. var input ScanRequest
  48. b, err := io.ReadAll(r.Body)
  49. defer r.Body.Close()
  50. if err != nil {
  51. fmt.Fprintf(w, "There was an error processing your request: %s", err)
  52. return
  53. }
  54. err = json.Unmarshal(b, &input)
  55. if err != nil {
  56. fmt.Fprintf(w, "There was an error processing your request: %s", err)
  57. return
  58. }
  59. subnetMap, err := GetNetworkAddresses(input.IpAddress)
  60. if err != nil {
  61. fmt.Fprintf(w, "There was an error processing your request: %s", err)
  62. }
  63. scanned := make(chan Host, len(subnetMap.Ipv4s))
  64. NetSweep(subnetMap.Ipv4s, RetrieveScanDirectives(), scanned)
  65. close(scanned)
  66. for host := range scanned {
  67. if len(host.ListeningPorts) > 0 {
  68. e.TableEntry.Execute(w, host)
  69. continue
  70. } else if host.Fqdn != "" {
  71. e.TableEntry.Execute(w, host)
  72. continue
  73. } else if host.PingResponse {
  74. e.TableEntry.Execute(w, host)
  75. continue
  76. }
  77. }
  78. }
  79. // handlers //
  80. type HtmlHandler struct {
  81. Home *template.Template // pointer to the HTML homepage
  82. DbHook TopologyDatabaseIO
  83. }
  84. /*
  85. Handler function for HTML serving
  86. :param w: http.ResponseWriter interface for sending data back
  87. :param r: pointer to the http.Request coming in
  88. */
  89. func (h *HtmlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  90. data, err := h.DbHook.All()
  91. if err != nil {
  92. fmt.Fprintf(w, "You have made it to the kyoketsu web server!\nThere was an error getting the db table, though.\n%s", err)
  93. }
  94. h.Home.Execute(w, data)
  95. }
  96. type AssetHandler struct {
  97. Root embed.FS // Should be able to use anything that implements the fs.FS interface for serving asset files
  98. EmbedRoot string // This is the root of the embeded file system
  99. RelPath string // The path that will be used for the handler, relative to the root of the webserver (/static, /assets, etc)
  100. }
  101. /*
  102. Handler function to serve out asset files (HTMX, bootstrap, pngs etc)
  103. :param w: http.ResponseWriter interface for sending data back to the caller
  104. :param r: pointer to an http.Request
  105. */
  106. func (a *AssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  107. var uripath string // the path from the request
  108. var pathSp []string // the path from the request split, so that we can point the request path to the embedded fs
  109. var assetPath []string // the cleaned path for the requested asset
  110. var fname string // filename of the requested asset
  111. var ctype string
  112. var b []byte
  113. var err error
  114. uripath = strings.TrimPrefix(r.URL.Path, a.RelPath)
  115. uripath = strings.Trim(uripath, "/")
  116. pathSp = strings.Split(uripath, "/")
  117. fname = pathSp[len(pathSp)-1]
  118. assetPath = append(assetPath, a.EmbedRoot)
  119. for i := 1; i < len(pathSp); i++ {
  120. assetPath = append(assetPath, pathSp[i])
  121. }
  122. b, err = a.Root.ReadFile(path.Join(assetPath...))
  123. if err != nil {
  124. fmt.Fprintf(w, "Error occured: %s. path split: '%s'\nAsset Path: %s", err, pathSp, assetPath)
  125. }
  126. switch {
  127. case strings.Contains(fname, "css"):
  128. ctype = "text/css"
  129. case strings.Contains(fname, "js"):
  130. ctype = "text/javascript"
  131. case strings.Contains(fname, "html"):
  132. ctype = "text/html"
  133. case strings.Contains(fname, "json"):
  134. ctype = "application/json"
  135. case strings.Contains(fname, "png"):
  136. ctype = "image/png"
  137. default:
  138. ctype = "text"
  139. }
  140. w.Header().Add("Content-Type", ctype)
  141. fmt.Fprint(w, string(b))
  142. }