websocket.go 3.8 KB

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