Router.coffee 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. metrics = require "metrics-sharelatex"
  2. logger = require "logger-sharelatex"
  3. settings = require "settings-sharelatex"
  4. WebsocketController = require "./WebsocketController"
  5. HttpController = require "./HttpController"
  6. HttpApiController = require "./HttpApiController"
  7. Utils = require "./Utils"
  8. bodyParser = require "body-parser"
  9. base64id = require("base64id")
  10. basicAuth = require('basic-auth-connect')
  11. httpAuth = basicAuth (user, pass)->
  12. isValid = user == settings.internal.realTime.user and pass == settings.internal.realTime.pass
  13. if !isValid
  14. logger.err user:user, pass:pass, "invalid login details"
  15. return isValid
  16. module.exports = Router =
  17. _handleError: (callback = ((error) ->), error, client, method, extraAttrs = {}) ->
  18. Utils.getClientAttributes client, ["project_id", "doc_id", "user_id"], (_, attrs) ->
  19. for key, value of extraAttrs
  20. attrs[key] = value
  21. attrs.client_id = client.id
  22. attrs.err = error
  23. if error.name == "CodedError"
  24. logger.warn attrs, error.message, code: error.code
  25. return callback {message: error.message, code: error.code}
  26. if error.message == 'unexpected arguments'
  27. logger.log attrs, 'unexpected arguments'
  28. metrics.inc 'unexpected-arguments', 1, { status: method }
  29. return callback { message: error.message }
  30. if error.message in ["not authorized", "doc updater could not load requested ops", "no project_id found on client"]
  31. logger.warn attrs, error.message
  32. return callback {message: error.message}
  33. else
  34. logger.error attrs, "server side error in #{method}"
  35. # Don't return raw error to prevent leaking server side info
  36. return callback {message: "Something went wrong in real-time service"}
  37. _handleInvalidArguments: (client, method, args) ->
  38. error = new Error("unexpected arguments")
  39. callback = args[args.length - 1]
  40. if typeof callback != 'function'
  41. callback = (() ->)
  42. attrs = {arguments: args}
  43. Router._handleError(callback, error, client, method, attrs)
  44. configure: (app, io, session) ->
  45. app.set("io", io)
  46. app.get "/clients", HttpController.getConnectedClients
  47. app.get "/clients/:client_id", HttpController.getConnectedClient
  48. app.post "/project/:project_id/message/:message", httpAuth, bodyParser.json(limit: "5mb"), HttpApiController.sendMessage
  49. app.post "/drain", httpAuth, HttpApiController.startDrain
  50. app.post "/client/:client_id/disconnect", httpAuth, HttpApiController.disconnectClient
  51. session.on 'connection', (error, client, session) ->
  52. client?.on "error", (err) ->
  53. logger.err { clientErr: err }, "socket.io client error"
  54. if client.connected
  55. client.emit("reconnectGracefully")
  56. client.disconnect()
  57. if settings.shutDownInProgress
  58. client.emit("connectionRejected", {message: "retry"})
  59. client.disconnect()
  60. return
  61. if client? and error?.message?.match(/could not look up session by key/)
  62. logger.warn err: error, client: client?, session: session?, "invalid session"
  63. # tell the client to reauthenticate if it has an invalid session key
  64. client.emit("connectionRejected", {message: "invalid session"})
  65. client.disconnect()
  66. return
  67. if error?
  68. logger.err err: error, client: client?, session: session?, "error when client connected"
  69. client?.emit("connectionRejected", {message: "error"})
  70. client?.disconnect()
  71. return
  72. # send positive confirmation that the client has a valid connection
  73. client.publicId = 'P.' + base64id.generateId()
  74. client.emit("connectionAccepted", null, client.publicId)
  75. metrics.inc('socket-io.connection')
  76. metrics.gauge('socket-io.clients', io.sockets.clients()?.length)
  77. logger.log session: session, client_id: client.id, "client connected"
  78. if session?.passport?.user?
  79. user = session.passport.user
  80. else if session?.user?
  81. user = session.user
  82. else
  83. user = {_id: "anonymous-user"}
  84. client.on "joinProject", (data = {}, callback) ->
  85. if typeof callback != 'function'
  86. return Router._handleInvalidArguments(client, 'joinProject', arguments)
  87. if data.anonymousAccessToken
  88. user.anonymousAccessToken = data.anonymousAccessToken
  89. WebsocketController.joinProject client, user, data.project_id, (err, args...) ->
  90. if err?
  91. Router._handleError callback, err, client, "joinProject", {project_id: data.project_id, user_id: user?.id}
  92. else
  93. callback(null, args...)
  94. client.on "disconnect", () ->
  95. metrics.inc('socket-io.disconnect')
  96. metrics.gauge('socket-io.clients', io.sockets.clients()?.length - 1)
  97. WebsocketController.leaveProject io, client, (err) ->
  98. if err?
  99. Router._handleError null, err, client, "leaveProject"
  100. # Variadic. The possible arguments:
  101. # doc_id, callback
  102. # doc_id, fromVersion, callback
  103. # doc_id, options, callback
  104. # doc_id, fromVersion, options, callback
  105. client.on "joinDoc", (doc_id, fromVersion, options, callback) ->
  106. if typeof fromVersion == "function" and !options
  107. callback = fromVersion
  108. fromVersion = -1
  109. options = {}
  110. else if typeof fromVersion == "number" and typeof options == "function"
  111. callback = options
  112. options = {}
  113. else if typeof fromVersion == "object" and typeof options == "function"
  114. callback = options
  115. options = fromVersion
  116. fromVersion = -1
  117. else if typeof fromVersion == "number" and typeof options == "object" and typeof callback == 'function'
  118. # Called with 4 args, things are as expected
  119. else
  120. return Router._handleInvalidArguments(client, 'joinDoc', arguments)
  121. WebsocketController.joinDoc client, doc_id, fromVersion, options, (err, args...) ->
  122. if err?
  123. Router._handleError callback, err, client, "joinDoc", {doc_id, fromVersion}
  124. else
  125. callback(null, args...)
  126. client.on "leaveDoc", (doc_id, callback) ->
  127. if typeof callback != 'function'
  128. return Router._handleInvalidArguments(client, 'leaveDoc', arguments)
  129. WebsocketController.leaveDoc client, doc_id, (err, args...) ->
  130. if err?
  131. Router._handleError callback, err, client, "leaveDoc"
  132. else
  133. callback(null, args...)
  134. client.on "clientTracking.getConnectedUsers", (callback = (error, users) ->) ->
  135. if typeof callback != 'function'
  136. return Router._handleInvalidArguments(client, 'clientTracking.getConnectedUsers', arguments)
  137. WebsocketController.getConnectedUsers client, (err, users) ->
  138. if err?
  139. Router._handleError callback, err, client, "clientTracking.getConnectedUsers"
  140. else
  141. callback(null, users)
  142. client.on "clientTracking.updatePosition", (cursorData, callback = (error) ->) ->
  143. if typeof callback != 'function'
  144. return Router._handleInvalidArguments(client, 'clientTracking.updatePosition', arguments)
  145. WebsocketController.updateClientPosition client, cursorData, (err) ->
  146. if err?
  147. Router._handleError callback, err, client, "clientTracking.updatePosition"
  148. else
  149. callback()
  150. client.on "applyOtUpdate", (doc_id, update, callback = (error) ->) ->
  151. if typeof callback != 'function'
  152. return Router._handleInvalidArguments(client, 'applyOtUpdate', arguments)
  153. WebsocketController.applyOtUpdate client, doc_id, update, (err) ->
  154. if err?
  155. Router._handleError callback, err, client, "applyOtUpdate", {doc_id, update}
  156. else
  157. callback()