websocket.go 4.5 KB

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