CompileController.coffee 9.9 KB

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