CompileController.coffee 9.8 KB

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