websocket.go 4.1 KB

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