webserver.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 []int) {
  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 []int
  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)
  64. go func() {
  65. for x := range scanned {
  66. if len(x.ListeningPorts) > 0 {
  67. e.TableEntry.Execute(w, x)
  68. fmt.Print(" |-|-|-| :::: HOST FOUND :::: |-|-|-|\n==================||==================\n")
  69. fmt.Printf("IPv4 Address: %s\nListening Ports: %v\n=====================================\n", x.IpAddress, x.ListeningPorts)
  70. host, err := e.DbHook.GetByIP(x.IpAddress)
  71. if err != nil {
  72. if err != ErrNotExists {
  73. log.Fatal(err, " Couldnt access the database. Fatal error.\n")
  74. }
  75. _, err = e.DbHook.Create(x)
  76. if err != nil {
  77. log.Fatal(err, " Fatal error trying to read the database.\n")
  78. }
  79. continue
  80. }
  81. _, err = e.DbHook.Update(host.Id, x)
  82. if err != nil {
  83. log.Fatal(err, " fatal error when updating a record.\n")
  84. }
  85. }
  86. }
  87. }()
  88. NetSweep(subnetMap.Ipv4s, RetrieveScanDirectives(), scanned)
  89. /*
  90. rec, err := e.DbHook.GetByIP(host.IpAddress)
  91. if err != nil {
  92. if err != ErrNotExists {
  93. log.Fatal(err, "There was a fatal error querying the database\n")
  94. }
  95. _, err = e.DbHook.Create(host)
  96. if err != nil {
  97. log.Fatal(err, "There was a fatal error creating this record in the database.\n")
  98. }
  99. continue
  100. }
  101. _, err = e.DbHook.Update(rec.Id, host)
  102. if err != nil {
  103. log.Fatal(err, "there was a fatal error updating this record: ", rec)
  104. }
  105. continue
  106. */
  107. // not adding these to the database because this isnt really that important
  108. }
  109. // handlers //
  110. type HtmlHandler struct {
  111. Home *template.Template // pointer to the HTML homepage
  112. DbHook TopologyDatabaseIO
  113. }
  114. /*
  115. Handler function for HTML serving
  116. :param w: http.ResponseWriter interface for sending data back
  117. :param r: pointer to the http.Request coming in
  118. */
  119. func (h *HtmlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  120. data, err := h.DbHook.All()
  121. if err != nil {
  122. fmt.Fprintf(w, "You have made it to the kyoketsu web server!\nThere was an error getting the db table, though.\n%s", err)
  123. }
  124. h.Home.Execute(w, data)
  125. }
  126. type AssetHandler struct {
  127. Root embed.FS // Should be able to use anything that implements the fs.FS interface for serving asset files
  128. EmbedRoot string // This is the root of the embeded file system
  129. RelPath string // The path that will be used for the handler, relative to the root of the webserver (/static, /assets, etc)
  130. }
  131. /*
  132. Handler function to serve out asset files (HTMX, bootstrap, pngs etc)
  133. :param w: http.ResponseWriter interface for sending data back to the caller
  134. :param r: pointer to an http.Request
  135. */
  136. func (a *AssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  137. var uripath string // the path from the request
  138. var pathSp []string // the path from the request split, so that we can point the request path to the embedded fs
  139. var assetPath []string // the cleaned path for the requested asset
  140. var fname string // filename of the requested asset
  141. var ctype string
  142. var b []byte
  143. var err error
  144. uripath = strings.TrimPrefix(r.URL.Path, a.RelPath)
  145. uripath = strings.Trim(uripath, "/")
  146. pathSp = strings.Split(uripath, "/")
  147. fname = pathSp[len(pathSp)-1]
  148. assetPath = append(assetPath, a.EmbedRoot)
  149. for i := 1; i < len(pathSp); i++ {
  150. assetPath = append(assetPath, pathSp[i])
  151. }
  152. b, err = a.Root.ReadFile(path.Join(assetPath...))
  153. if err != nil {
  154. fmt.Fprintf(w, "Error occured: %s. path split: '%s'\nAsset Path: %s", err, pathSp, assetPath)
  155. }
  156. switch {
  157. case strings.Contains(fname, "css"):
  158. ctype = "text/css"
  159. case strings.Contains(fname, "js"):
  160. ctype = "text/javascript"
  161. case strings.Contains(fname, "html"):
  162. ctype = "text/html"
  163. case strings.Contains(fname, "json"):
  164. ctype = "application/json"
  165. case strings.Contains(fname, "png"):
  166. ctype = "image/png"
  167. default:
  168. ctype = "text"
  169. }
  170. w.Header().Add("Content-Type", ctype)
  171. fmt.Fprint(w, string(b))
  172. }