CompileController.coffee 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. Metrics = require "metrics-sharelatex"
  2. Project = require("../../models/Project").Project
  3. CompileManager = require("./CompileManager")
  4. ClsiManager = require("./ClsiManager")
  5. logger = require "logger-sharelatex"
  6. request = require "request"
  7. Settings = require "settings-sharelatex"
  8. AuthenticationController = require "../Authentication/AuthenticationController"
  9. UserGetter = require "../User/UserGetter"
  10. RateLimiter = require("../../infrastructure/RateLimiter")
  11. ClsiCookieManager = require("./ClsiCookieManager")
  12. Path = require("path")
  13. module.exports = CompileController =
  14. compile: (req, res, next = (error) ->) ->
  15. res.setTimeout(5 * 60 * 1000)
  16. project_id = req.params.Project_id
  17. isAutoCompile = !!req.query?.auto_compile
  18. user_id = AuthenticationController.getLoggedInUserId req
  19. options = {
  20. isAutoCompile: isAutoCompile
  21. }
  22. if req.body?.rootDoc_id?
  23. options.rootDoc_id = req.body.rootDoc_id
  24. else if req.body?.settingsOverride?.rootDoc_id? # Can be removed after deploy
  25. options.rootDoc_id = req.body.settingsOverride.rootDoc_id
  26. if req.body?.compiler
  27. options.compiler = req.body.compiler
  28. if req.body?.draft
  29. options.draft = req.body.draft
  30. if req.body?.check in ['validate', 'error', 'silent']
  31. options.check = req.body.check
  32. if req.body?.incrementalCompilesEnabled
  33. options.incrementalCompilesEnabled = true
  34. logger.log {options:options, project_id:project_id, user_id:user_id}, "got compile request"
  35. CompileManager.compile project_id, user_id, options, (error, status, outputFiles, clsiServerId, limits, validationProblems) ->
  36. return next(error) if error?
  37. res.contentType("application/json")
  38. res.status(200).send JSON.stringify {
  39. status: status
  40. outputFiles: outputFiles
  41. compileGroup: limits?.compileGroup
  42. clsiServerId:clsiServerId
  43. validationProblems:validationProblems
  44. }
  45. stopCompile: (req, res, next = (error) ->) ->
  46. project_id = req.params.Project_id
  47. user_id = AuthenticationController.getLoggedInUserId req
  48. logger.log {project_id:project_id, user_id:user_id}, "stop compile request"
  49. CompileManager.stopCompile project_id, user_id, (error) ->
  50. return next(error) if error?
  51. res.status(200).send()
  52. _compileAsUser: (req, callback) ->
  53. # callback with user_id if per-user, undefined otherwise
  54. if not Settings.disablePerUserCompiles
  55. user_id = AuthenticationController.getLoggedInUserId req
  56. return callback(null, user_id)
  57. else
  58. callback() # do a per-project compile, not per-user
  59. _downloadAsUser: (req, callback) ->
  60. # callback with user_id if per-user, undefined otherwise
  61. if not Settings.disablePerUserCompiles
  62. user_id = AuthenticationController.getLoggedInUserId req
  63. return callback(null, user_id)
  64. else
  65. callback() # do a per-project compile, not per-user
  66. downloadPdf: (req, res, next = (error) ->)->
  67. Metrics.inc "pdf-downloads"
  68. project_id = req.params.Project_id
  69. isPdfjsPartialDownload = req.query?.pdfng
  70. rateLimit = (callback)->
  71. if isPdfjsPartialDownload
  72. callback null, true
  73. else
  74. rateLimitOpts =
  75. endpointName: "full-pdf-download"
  76. throttle: 1000
  77. subjectName : req.ip
  78. timeInterval : 60 * 60
  79. RateLimiter.addCount rateLimitOpts, callback
  80. Project.findById project_id, {name: 1}, (err, project)->
  81. res.contentType("application/pdf")
  82. if !!req.query.popupDownload
  83. logger.log project_id: project_id, "download pdf as popup download"
  84. res.setContentDisposition('attachment', {filename: "#{project.getSafeProjectName()}.pdf"})
  85. else
  86. logger.log project_id: project_id, "download pdf to embed in browser"
  87. res.setContentDisposition('', {filename: "#{project.getSafeProjectName()}.pdf"})
  88. rateLimit (err, canContinue)->
  89. if err?
  90. logger.err err:err, "error checking rate limit for pdf download"
  91. return res.send 500
  92. else if !canContinue
  93. logger.log project_id:project_id, ip:req.ip, "rate limit hit downloading pdf"
  94. res.send 500
  95. else
  96. CompileController._downloadAsUser req, (error, user_id) ->
  97. url = CompileController._getFileUrl project_id, user_id, req.params.build_id, "output.pdf"
  98. CompileController.proxyToClsi(project_id, url, req, res, next)
  99. deleteAuxFiles: (req, res, next) ->
  100. project_id = req.params.Project_id
  101. CompileController._compileAsUser req, (error, user_id) ->
  102. return next(error) if error?
  103. CompileManager.deleteAuxFiles project_id, user_id, (error) ->
  104. return next(error) if error?
  105. res.sendStatus(200)
  106. # this is only used by templates, so is not called with a user_id
  107. compileAndDownloadPdf: (req, res, next)->
  108. project_id = req.params.project_id
  109. # pass user_id as null, since templates are an "anonymous" compile
  110. CompileManager.compile project_id, null, {}, (err)->
  111. if err?
  112. logger.err err:err, project_id:project_id, "something went wrong compile and downloading pdf"
  113. res.sendStatus 500
  114. url = "/project/#{project_id}/output/output.pdf"
  115. CompileController.proxyToClsi project_id, url, req, res, next
  116. getFileFromClsi: (req, res, next = (error) ->) ->
  117. project_id = req.params.Project_id
  118. CompileController._downloadAsUser req, (error, user_id) ->
  119. return next(error) if error?
  120. url = CompileController._getFileUrl project_id, user_id, req.params.build_id, req.params.file
  121. CompileController.proxyToClsi(project_id, url, req, res, next)
  122. # compute a GET file url for a given project, user (optional), build (optional) and file
  123. _getFileUrl: (project_id, user_id, build_id, file) ->
  124. if user_id? and build_id?
  125. url = "/project/#{project_id}/user/#{user_id}/build/#{build_id}/output/#{file}"
  126. else if user_id?
  127. url = "/project/#{project_id}/user/#{user_id}/output/#{file}"
  128. else if build_id?
  129. url = "/project/#{project_id}/build/#{build_id}/output/#{file}"
  130. else
  131. url = "/project/#{project_id}/output/#{file}"
  132. return url
  133. # compute a POST url for a project, user (optional) and action
  134. _getUrl: (project_id, user_id, action) ->
  135. path = "/project/#{project_id}"
  136. path += "/user/#{user_id}" if user_id?
  137. return "#{path}/#{action}"
  138. proxySyncPdf: (req, res, next = (error) ->) ->
  139. project_id = req.params.Project_id
  140. {page, h, v} = req.query
  141. if not page?.match(/^\d+$/)
  142. return next(new Error("invalid page parameter"))
  143. if not h?.match(/^-?\d+\.\d+$/)
  144. return next(new Error("invalid h parameter"))
  145. if not v?.match(/^-?\d+\.\d+$/)
  146. return next(new Error("invalid v parameter"))
  147. # whether this request is going to a per-user container
  148. CompileController._compileAsUser req, (error, user_id) ->
  149. return next(error) if error?
  150. url = CompileController._getUrl(project_id, user_id, "sync/pdf")
  151. destination = {url: url, qs: {page, h, v}}
  152. CompileController.proxyToClsi(project_id, destination, req, res, next)
  153. proxySyncCode: (req, res, next = (error) ->) ->
  154. project_id = req.params.Project_id
  155. {file, line, column} = req.query
  156. if not file?
  157. return next(new Error("missing file parameter"))
  158. # Check that we are dealing with a simple file path (this is not
  159. # strictly needed because synctex uses this parameter as a label
  160. # to look up in the synctex output, and does not open the file
  161. # itself). Since we have valid synctex paths like foo/./bar we
  162. # allow those by replacing /./ with /
  163. testPath = file.replace '/./', '/'
  164. if Path.resolve("/", testPath) isnt "/#{testPath}"
  165. return next(new Error("invalid file parameter"))
  166. if not line?.match(/^\d+$/)
  167. return next(new Error("invalid line parameter"))
  168. if not column?.match(/^\d+$/)
  169. return next(new Error("invalid column parameter"))
  170. CompileController._compileAsUser req, (error, user_id) ->
  171. return next(error) if error?
  172. url = CompileController._getUrl(project_id, user_id, "sync/code")
  173. destination = {url:url, qs: {file, line, column}}
  174. CompileController.proxyToClsi(project_id, destination, req, res, next)
  175. proxyToClsi: (project_id, url, req, res, next = (error) ->) ->
  176. if req.query?.compileGroup
  177. CompileController.proxyToClsiWithLimits(project_id, url, {compileGroup: req.query.compileGroup}, req, res, next)
  178. else
  179. CompileManager.getProjectCompileLimits project_id, (error, limits) ->
  180. return next(error) if error?
  181. CompileController.proxyToClsiWithLimits(project_id, url, limits, req, res, next)
  182. proxyToClsiWithLimits: (project_id, url, limits, req, res, next = (error) ->) ->
  183. ClsiCookieManager.getCookieJar project_id, (err, jar)->
  184. if err?
  185. logger.err err:err, "error getting cookie jar for clsi request"
  186. return callback(err)
  187. # expand any url parameter passed in as {url:..., qs:...}
  188. if typeof url is "object"
  189. {url, qs} = url
  190. compilerUrl = Settings.apis.clsi.url
  191. url = "#{compilerUrl}#{url}"
  192. logger.log url: url, "proxying to CLSI"
  193. oneMinute = 60 * 1000
  194. # the base request
  195. options = { url: url, method: req.method, timeout: oneMinute, jar : jar }
  196. # add any provided query string
  197. options.qs = qs if qs?
  198. # if we have a build parameter, pass it through to the clsi
  199. if req.query?.pdfng && req.query?.build? # only for new pdf viewer
  200. options.qs ?= {}
  201. options.qs.build = req.query.build
  202. # if we are byte serving pdfs, pass through If-* and Range headers
  203. # do not send any others, there's a proxying loop if Host: is passed!
  204. if req.query?.pdfng
  205. newHeaders = {}
  206. for h, v of req.headers
  207. newHeaders[h] = req.headers[h] if h.match /^(If-|Range)/i
  208. options.headers = newHeaders
  209. proxy = request(options)
  210. proxy.pipe(res)
  211. proxy.on "error", (error) ->
  212. logger.warn err: error, url: url, "CLSI proxy error"
  213. wordCount: (req, res, next) ->
  214. project_id = req.params.Project_id
  215. file = req.query.file || false
  216. CompileController._compileAsUser req, (error, user_id) ->
  217. return next(error) if error?
  218. CompileManager.wordCount project_id, user_id, file, (error, body) ->
  219. return next(error) if error?
  220. res.contentType("application/json")
  221. res.send body