websocket.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. package websocket
  2. import (
  3. pb "github.com/OliveTin/OliveTin/gen/grpc"
  4. "github.com/OliveTin/OliveTin/internal/executor"
  5. ws "github.com/gorilla/websocket"
  6. log "github.com/sirupsen/logrus"
  7. "google.golang.org/protobuf/encoding/protojson"
  8. "google.golang.org/protobuf/reflect/protoreflect"
  9. "net/http"
  10. "sync"
  11. )
  12. var upgrader = ws.Upgrader{
  13. CheckOrigin: checkOriginPermissive,
  14. }
  15. var (
  16. sendmutex = sync.Mutex{}
  17. )
  18. type WebsocketClient struct {
  19. conn *ws.Conn
  20. }
  21. var clients []*WebsocketClient
  22. var marshalOptions = protojson.MarshalOptions{
  23. UseProtoNames: false, // eg: canExec for js instead of can_exec from protobuf
  24. EmitUnpopulated: true,
  25. }
  26. func OnConfigChanged() {
  27. evt := &pb.EventConfigChanged{}
  28. broadcast(evt)
  29. }
  30. var ExecutionListener WebsocketExecutionListener
  31. type WebsocketExecutionListener struct{}
  32. func (WebsocketExecutionListener) OnExecutionStarted(title string) {
  33. /*
  34. broadcast(ExecutionStarted{
  35. Type: "ExecutionStarted",
  36. Action: title,
  37. });
  38. */
  39. }
  40. func OnEntityChanged() {
  41. broadcast(&pb.EventEntityChanged{})
  42. }
  43. /*
  44. The default checkOrigin function checks that the origin (browser) matches the
  45. request origin. However in OliveTin we expect many users to deliberately proxy
  46. the connection with reverse proxies.
  47. So, we just permit any origin. After some searching I'm not sure if this exposes
  48. OliveTin to security issues, but it seems probably not. It would be possible to
  49. create a config option like PermitWebsocketConnectionsFrom or something, but
  50. I'd prefer if OliveTin works as much as possible "out of the box".
  51. If this does expose OliveTin to security issues, it will be changed in the
  52. future obviously.
  53. */
  54. func checkOriginPermissive(r *http.Request) bool {
  55. return true
  56. }
  57. func (WebsocketExecutionListener) OnExecutionFinished(logEntry *executor.InternalLogEntry) {
  58. evt := &pb.EventExecutionFinished{
  59. LogEntry: &pb.LogEntry{
  60. ActionTitle: logEntry.ActionTitle,
  61. ActionIcon: logEntry.ActionIcon,
  62. ActionId: logEntry.ActionId,
  63. DatetimeStarted: logEntry.DatetimeStarted.Format("2006-01-02 15:04:05"),
  64. DatetimeFinished: logEntry.DatetimeFinished.Format("2006-01-02 15:04:05"),
  65. Stdout: logEntry.Stdout,
  66. Stderr: logEntry.Stderr,
  67. TimedOut: logEntry.TimedOut,
  68. Blocked: logEntry.Blocked,
  69. ExitCode: logEntry.ExitCode,
  70. Tags: logEntry.Tags,
  71. ExecutionTrackingId: logEntry.ExecutionTrackingID,
  72. ExecutionStarted: logEntry.ExecutionStarted,
  73. ExecutionFinished: logEntry.ExecutionFinished,
  74. },
  75. }
  76. broadcast(evt)
  77. }
  78. func broadcast(pbmsg protoreflect.ProtoMessage) {
  79. payload, err := marshalOptions.Marshal(pbmsg)
  80. if err != nil {
  81. log.Errorf("websocket marshal error: %v", err)
  82. return
  83. }
  84. messageType := pbmsg.ProtoReflect().Descriptor().FullName()
  85. // <EVIL>
  86. // So, the websocket wants to encode messages using the same protomarshaller
  87. // as the REST API - this gives consistency instead of using encoding/json
  88. // and allows us to set specific marshalOptions.
  89. //
  90. // However, the protomarshaller will marshal the type, but the JavaScript at
  91. // the other end has no idea what type this object is - as we're just sending
  92. // it as JSON over the websocket.
  93. //
  94. // Therefore, we wrap the nicely marsheled bytes in a hacky JSON string
  95. // literal and encode that string just with a byte array cast.
  96. hackyMessageEnvelope := "{\"type\": \"" + messageType + "\", \"payload\": "
  97. hackyMessage := []byte{}
  98. hackyMessage = append(hackyMessage, []byte(hackyMessageEnvelope)...)
  99. hackyMessage = append(hackyMessage, payload...)
  100. hackyMessage = append(hackyMessage, []byte("}")...)
  101. // </EVIL>
  102. sendmutex.Lock()
  103. for _, client := range clients {
  104. client.conn.WriteMessage(ws.TextMessage, hackyMessage)
  105. }
  106. sendmutex.Unlock()
  107. }
  108. func (c *WebsocketClient) messageLoop() {
  109. for {
  110. mt, message, err := c.conn.ReadMessage()
  111. if err != nil {
  112. log.Debugf("err: %v", err)
  113. break
  114. }
  115. log.Tracef("websocket recv: %s %d", message, mt)
  116. }
  117. }
  118. func HandleWebsocket(w http.ResponseWriter, r *http.Request) bool {
  119. c, err := upgrader.Upgrade(w, r, nil)
  120. if err != nil {
  121. log.Warnf("Websocket issue: %v", err)
  122. return false
  123. }
  124. // defer c.Close()
  125. wsclient := &WebsocketClient{
  126. conn: c,
  127. }
  128. clients = append(clients, wsclient)
  129. go wsclient.messageLoop()
  130. return true
  131. }