CompileController.coffee 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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")(Settings.apis.clsi?.backendGroupName)
  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. pdfDownloadDomain: Settings.pdfDownloadDomain
  46. }
  47. stopCompile: (req, res, next = (error) ->) ->
  48. project_id = req.params.Project_id
  49. user_id = AuthenticationController.getLoggedInUserId req
  50. logger.log {project_id:project_id, user_id:user_id}, "stop compile request"
  51. CompileManager.stopCompile project_id, user_id, (error) ->
  52. return next(error) if error?
  53. res.status(200).send()
  54. # Used for submissions through the public API
  55. compileSubmission: (req, res, next = (error) ->) ->
  56. res.setTimeout(5 * 60 * 1000)
  57. submission_id = req.params.submission_id
  58. options = {}
  59. if req.body?.rootResourcePath?
  60. options.rootResourcePath = req.body.rootResourcePath
  61. if req.body?.compiler
  62. options.compiler = req.body.compiler
  63. if req.body?.draft
  64. options.draft = req.body.draft
  65. if req.body?.check in ['validate', 'error', 'silent']
  66. options.check = req.body.check
  67. options.compileGroup = req.body?.compileGroup || Settings.defaultFeatures.compileGroup
  68. options.timeout = req.body?.timeout || Settings.defaultFeatures.compileTimeout
  69. logger.log {options:options, submission_id:submission_id}, "got compileSubmission request"
  70. ClsiManager.sendExternalRequest submission_id, req.body, options, (error, status, outputFiles, clsiServerId, validationProblems) ->
  71. return next(error) if error?
  72. logger.log {submission_id:submission_id, files:outputFiles}, "compileSubmission output files"
  73. res.contentType("application/json")
  74. res.status(200).send JSON.stringify {
  75. status: status
  76. outputFiles: outputFiles
  77. clsiServerId: clsiServerId
  78. validationProblems: validationProblems
  79. }
  80. _compileAsUser: (req, callback) ->
  81. # callback with user_id if per-user, undefined otherwise
  82. if not Settings.disablePerUserCompiles
  83. user_id = AuthenticationController.getLoggedInUserId req
  84. return callback(null, user_id)
  85. else
  86. callback() # do a per-project compile, not per-user
  87. _downloadAsUser: (req, callback) ->
  88. # callback with user_id if per-user, undefined otherwise
  89. if not Settings.disablePerUserCompiles
  90. user_id = AuthenticationController.getLoggedInUserId req
  91. return callback(null, user_id)
  92. else
  93. callback() # do a per-project compile, not per-user
  94. downloadPdf: (req, res, next = (error) ->)->
  95. Metrics.inc "pdf-downloads"
  96. project_id = req.params.Project_id
  97. isPdfjsPartialDownload = req.query?.pdfng
  98. rateLimit = (callback)->
  99. if isPdfjsPartialDownload
  100. callback null, true
  101. else
  102. rateLimitOpts =
  103. endpointName: "full-pdf-download"
  104. throttle: 1000
  105. subjectName : req.ip
  106. timeInterval : 60 * 60
  107. RateLimiter.addCount rateLimitOpts, callback
  108. ProjectGetter.getProject project_id, name: 1, (err, project) ->
  109. res.contentType("application/pdf")
  110. filename = "#{CompileController._getSafeProjectName(project)}.pdf"
  111. if !!req.query.popupDownload
  112. logger.log project_id: project_id, "download pdf as popup download"
  113. res.setContentDisposition('attachment', {filename})
  114. else
  115. logger.log project_id: project_id, "download pdf to embed in browser"
  116. res.setContentDisposition('', {filename})
  117. rateLimit (err, canContinue)->
  118. if err?
  119. logger.err err:err, "error checking rate limit for pdf download"
  120. return res.send 500
  121. else if !canContinue
  122. logger.log project_id:project_id, ip:req.ip, "rate limit hit downloading pdf"
  123. res.send 500
  124. else
  125. CompileController._downloadAsUser req, (error, user_id) ->
  126. url = CompileController._getFileUrl project_id, user_id, req.params.build_id, "output.pdf"
  127. CompileController.proxyToClsi(project_id, url, req, res, next)
  128. _getSafeProjectName: (project) ->
  129. safeProjectName = project.name.replace(new RegExp("\\W", "g"), '_')
  130. sanitize.escape(safeProjectName)
  131. deleteAuxFiles: (req, res, next) ->
  132. project_id = req.params.Project_id
  133. CompileController._compileAsUser req, (error, user_id) ->
  134. return next(error) if error?
  135. CompileManager.deleteAuxFiles project_id, user_id, (error) ->
  136. return next(error) if error?
  137. res.sendStatus(200)
  138. # this is only used by templates, so is not called with a user_id
  139. compileAndDownloadPdf: (req, res, next)->
  140. project_id = req.params.project_id
  141. # pass user_id as null, since templates are an "anonymous" compile
  142. CompileManager.compile project_id, null, {}, (err)->
  143. if err?
  144. logger.err err:err, project_id:project_id, "something went wrong compile and downloading pdf"
  145. res.sendStatus 500
  146. url = "/project/#{project_id}/output/output.pdf"
  147. CompileController.proxyToClsi project_id, url, req, res, next
  148. getFileFromClsi: (req, res, next = (error) ->) ->
  149. project_id = req.params.Project_id
  150. CompileController._downloadAsUser req, (error, user_id) ->
  151. return next(error) if error?
  152. url = CompileController._getFileUrl project_id, user_id, req.params.build_id, req.params.file
  153. CompileController.proxyToClsi(project_id, url, req, res, next)
  154. getFileFromClsiWithoutUser: (req, res, next = (error) ->) ->
  155. submission_id = req.params.submission_id
  156. url = CompileController._getFileUrl submission_id, null, req.params.build_id, req.params.file
  157. limits = { compileGroup: req.body?.compileGroup || Settings.defaultFeatures.compileGroup }
  158. CompileController.proxyToClsiWithLimits(submission_id, url, limits, req, res, next)
  159. # compute a GET file url for a given project, user (optional), build (optional) and file
  160. _getFileUrl: (project_id, user_id, build_id, file) ->
  161. if user_id? and build_id?
  162. url = "/project/#{project_id}/user/#{user_id}/build/#{build_id}/output/#{file}"
  163. else if user_id?
  164. url = "/project/#{project_id}/user/#{user_id}/output/#{file}"
  165. else if build_id?
  166. url = "/project/#{project_id}/build/#{build_id}/output/#{file}"
  167. else
  168. url = "/project/#{project_id}/output/#{file}"
  169. return url
  170. # compute a POST url for a project, user (optional) and action
  171. _getUrl: (project_id, user_id, action) ->
  172. path = "/project/#{project_id}"
  173. path += "/user/#{user_id}" if user_id?
  174. return "#{path}/#{action}"
  175. proxySyncPdf: (req, res, next = (error) ->) ->
  176. project_id = req.params.Project_id
  177. {page, h, v} = req.query
  178. if not page?.match(/^\d+$/)
  179. return next(new Error("invalid page parameter"))
  180. if not h?.match(/^-?\d+\.\d+$/)
  181. return next(new Error("invalid h parameter"))
  182. if not v?.match(/^-?\d+\.\d+$/)
  183. return next(new Error("invalid v parameter"))
  184. # whether this request is going to a per-user container
  185. CompileController._compileAsUser req, (error, user_id) ->
  186. return next(error) if error?
  187. url = CompileController._getUrl(project_id, user_id, "sync/pdf")
  188. destination = {url: url, qs: {page, h, v}}
  189. CompileController.proxyToClsi(project_id, destination, req, res, next)
  190. proxySyncCode: (req, res, next = (error) ->) ->
  191. project_id = req.params.Project_id
  192. {file, line, column} = req.query
  193. if not file?
  194. return next(new Error("missing file parameter"))
  195. # Check that we are dealing with a simple file path (this is not
  196. # strictly needed because synctex uses this parameter as a label
  197. # to look up in the synctex output, and does not open the file
  198. # itself). Since we have valid synctex paths like foo/./bar we
  199. # allow those by replacing /./ with /
  200. testPath = file.replace '/./', '/'
  201. if Path.resolve("/", testPath) isnt "/#{testPath}"
  202. return next(new Error("invalid file parameter"))
  203. if not line?.match(/^\d+$/)
  204. return next(new Error("invalid line parameter"))
  205. if not column?.match(/^\d+$/)
  206. return next(new Error("invalid column parameter"))
  207. CompileController._compileAsUser req, (error, user_id) ->
  208. return next(error) if error?
  209. url = CompileController._getUrl(project_id, user_id, "sync/code")
  210. destination = {url:url, qs: {file, line, column}}
  211. CompileController.proxyToClsi(project_id, destination, req, res, next)
  212. proxyToClsi: (project_id, url, req, res, next = (error) ->) ->
  213. if req.query?.compileGroup
  214. CompileController.proxyToClsiWithLimits(project_id, url, {compileGroup: req.query.compileGroup}, req, res, next)
  215. else
  216. CompileManager.getProjectCompileLimits project_id, (error, limits) ->
  217. return next(error) if error?
  218. CompileController.proxyToClsiWithLimits(project_id, url, limits, req, res, next)
  219. proxyToClsiWithLimits: (project_id, url, limits, req, res, next = (error) ->) ->
  220. ClsiCookieManager.getCookieJar project_id, (err, jar)->
  221. if err?
  222. logger.err err:err, "error getting cookie jar for clsi request"
  223. return callback(err)
  224. # expand any url parameter passed in as {url:..., qs:...}
  225. if typeof url is "object"
  226. {url, qs} = url
  227. compilerUrl = Settings.apis.clsi.url
  228. url = "#{compilerUrl}#{url}"
  229. logger.log url: url, "proxying to CLSI"
  230. oneMinute = 60 * 1000
  231. # the base request
  232. options = { url: url, method: req.method, timeout: oneMinute, jar : jar }
  233. # add any provided query string
  234. options.qs = qs if qs?
  235. # if we have a build parameter, pass it through to the clsi
  236. if req.query?.pdfng && req.query?.build? # only for new pdf viewer
  237. options.qs ?= {}
  238. options.qs.build = req.query.build
  239. # if we are byte serving pdfs, pass through If-* and Range headers
  240. # do not send any others, there's a proxying loop if Host: is passed!
  241. if req.query?.pdfng
  242. newHeaders = {}
  243. for h, v of req.headers
  244. newHeaders[h] = req.headers[h] if /^(If-|Range)/i.test(h)
  245. options.headers = newHeaders
  246. proxy = request(options)
  247. proxy.pipe(res)
  248. proxy.on "error", (error) ->
  249. logger.warn err: error, url: url, "CLSI proxy error"
  250. wordCount: (req, res, next) ->
  251. project_id = req.params.Project_id
  252. file = req.query.file || false
  253. CompileController._compileAsUser req, (error, user_id) ->
  254. return next(error) if error?
  255. CompileManager.wordCount project_id, user_id, file, (error, body) ->
  256. return next(error) if error?
  257. res.contentType("application/json")
  258. res.send body