webclient.go 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package httpd
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "html/template"
  21. "io"
  22. "math"
  23. "net/http"
  24. "net/url"
  25. "os"
  26. "path"
  27. "path/filepath"
  28. "slices"
  29. "strconv"
  30. "strings"
  31. "time"
  32. "github.com/go-chi/render"
  33. "github.com/rs/xid"
  34. "github.com/sftpgo/sdk"
  35. "github.com/drakkan/sftpgo/v2/internal/common"
  36. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  37. "github.com/drakkan/sftpgo/v2/internal/logger"
  38. "github.com/drakkan/sftpgo/v2/internal/mfa"
  39. "github.com/drakkan/sftpgo/v2/internal/smtp"
  40. "github.com/drakkan/sftpgo/v2/internal/util"
  41. "github.com/drakkan/sftpgo/v2/internal/vfs"
  42. )
  43. const (
  44. templateClientDir = "webclient"
  45. templateClientBase = "base.html"
  46. templateClientFiles = "files.html"
  47. templateClientProfile = "profile.html"
  48. templateClientMFA = "mfa.html"
  49. templateClientEditFile = "editfile.html"
  50. templateClientShare = "share.html"
  51. templateClientShares = "shares.html"
  52. templateClientViewPDF = "viewpdf.html"
  53. templateShareLogin = "sharelogin.html"
  54. templateShareDownload = "sharedownload.html"
  55. templateUploadToShare = "shareupload.html"
  56. )
  57. // condResult is the result of an HTTP request precondition check.
  58. // See https://tools.ietf.org/html/rfc7232 section 3.
  59. type condResult int
  60. const (
  61. condNone condResult = iota
  62. condTrue
  63. condFalse
  64. )
  65. var (
  66. clientTemplates = make(map[string]*template.Template)
  67. unixEpochTime = time.Unix(0, 0)
  68. )
  69. // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
  70. func isZeroTime(t time.Time) bool {
  71. return t.IsZero() || t.Equal(unixEpochTime)
  72. }
  73. type baseClientPage struct {
  74. commonBasePage
  75. Title string
  76. CurrentURL string
  77. FilesURL string
  78. SharesURL string
  79. ShareURL string
  80. ProfileURL string
  81. PingURL string
  82. ChangePwdURL string
  83. LogoutURL string
  84. LoginURL string
  85. EditURL string
  86. MFAURL string
  87. CSRFToken string
  88. LoggedUser *dataprovider.User
  89. IsLoggedToShare bool
  90. Branding UIBranding
  91. }
  92. type dirMapping struct {
  93. DirName string
  94. Href string
  95. }
  96. type viewPDFPage struct {
  97. commonBasePage
  98. Title string
  99. URL string
  100. Branding UIBranding
  101. }
  102. type editFilePage struct {
  103. baseClientPage
  104. CurrentDir string
  105. FileURL string
  106. Path string
  107. Name string
  108. ReadOnly bool
  109. Data string
  110. }
  111. type filesPage struct {
  112. baseClientPage
  113. CurrentDir string
  114. DirsURL string
  115. FileActionsURL string
  116. CheckExistURL string
  117. DownloadURL string
  118. ViewPDFURL string
  119. FileURL string
  120. TasksURL string
  121. CanAddFiles bool
  122. CanCreateDirs bool
  123. CanRename bool
  124. CanDelete bool
  125. CanDownload bool
  126. CanShare bool
  127. CanCopy bool
  128. ShareUploadBaseURL string
  129. Error *util.I18nError
  130. Paths []dirMapping
  131. QuotaUsage *userQuotaUsage
  132. }
  133. type shareLoginPage struct {
  134. commonBasePage
  135. CurrentURL string
  136. Error *util.I18nError
  137. CSRFToken string
  138. Title string
  139. Branding UIBranding
  140. }
  141. type shareDownloadPage struct {
  142. baseClientPage
  143. DownloadLink string
  144. }
  145. type shareUploadPage struct {
  146. baseClientPage
  147. Share *dataprovider.Share
  148. UploadBasePath string
  149. }
  150. type clientMessagePage struct {
  151. baseClientPage
  152. Error *util.I18nError
  153. Success string
  154. Text string
  155. }
  156. type clientProfilePage struct {
  157. baseClientPage
  158. PublicKeys []string
  159. TLSCerts []string
  160. CanSubmit bool
  161. AllowAPIKeyAuth bool
  162. Email string
  163. Description string
  164. Error *util.I18nError
  165. }
  166. type changeClientPasswordPage struct {
  167. baseClientPage
  168. Error *util.I18nError
  169. }
  170. type clientMFAPage struct {
  171. baseClientPage
  172. TOTPConfigs []string
  173. TOTPConfig dataprovider.UserTOTPConfig
  174. GenerateTOTPURL string
  175. ValidateTOTPURL string
  176. SaveTOTPURL string
  177. RecCodesURL string
  178. Protocols []string
  179. RequiredProtocols []string
  180. }
  181. type clientSharesPage struct {
  182. baseClientPage
  183. BasePublicSharesURL string
  184. }
  185. type clientSharePage struct {
  186. baseClientPage
  187. Share *dataprovider.Share
  188. Error *util.I18nError
  189. IsAdd bool
  190. }
  191. type userQuotaUsage struct {
  192. QuotaSize int64
  193. QuotaFiles int
  194. UsedQuotaSize int64
  195. UsedQuotaFiles int
  196. UploadDataTransfer int64
  197. DownloadDataTransfer int64
  198. TotalDataTransfer int64
  199. UsedUploadDataTransfer int64
  200. UsedDownloadDataTransfer int64
  201. }
  202. func (u *userQuotaUsage) HasQuotaInfo() bool {
  203. if dataprovider.GetQuotaTracking() == 0 {
  204. return false
  205. }
  206. if u.HasDiskQuota() {
  207. return true
  208. }
  209. return u.HasTranferQuota()
  210. }
  211. func (u *userQuotaUsage) HasDiskQuota() bool {
  212. if u.QuotaSize > 0 || u.UsedQuotaSize > 0 {
  213. return true
  214. }
  215. return u.QuotaFiles > 0 || u.UsedQuotaFiles > 0
  216. }
  217. func (u *userQuotaUsage) HasTranferQuota() bool {
  218. if u.TotalDataTransfer > 0 || u.UploadDataTransfer > 0 || u.DownloadDataTransfer > 0 {
  219. return true
  220. }
  221. return u.UsedDownloadDataTransfer > 0 || u.UsedUploadDataTransfer > 0
  222. }
  223. func (u *userQuotaUsage) GetQuotaSize() string {
  224. if u.QuotaSize > 0 {
  225. return fmt.Sprintf("%s/%s", util.ByteCountIEC(u.UsedQuotaSize), util.ByteCountIEC(u.QuotaSize))
  226. }
  227. if u.UsedQuotaSize > 0 {
  228. return util.ByteCountIEC(u.UsedQuotaSize)
  229. }
  230. return ""
  231. }
  232. func (u *userQuotaUsage) GetQuotaFiles() string {
  233. if u.QuotaFiles > 0 {
  234. return fmt.Sprintf("%d/%d", u.UsedQuotaFiles, u.QuotaFiles)
  235. }
  236. if u.UsedQuotaFiles > 0 {
  237. return strconv.FormatInt(int64(u.UsedQuotaFiles), 10)
  238. }
  239. return ""
  240. }
  241. func (u *userQuotaUsage) GetQuotaSizePercentage() int {
  242. if u.QuotaSize > 0 {
  243. return int(math.Round(100 * float64(u.UsedQuotaSize) / float64(u.QuotaSize)))
  244. }
  245. return 0
  246. }
  247. func (u *userQuotaUsage) GetQuotaFilesPercentage() int {
  248. if u.QuotaFiles > 0 {
  249. return int(math.Round(100 * float64(u.UsedQuotaFiles) / float64(u.QuotaFiles)))
  250. }
  251. return 0
  252. }
  253. func (u *userQuotaUsage) IsQuotaSizeLow() bool {
  254. return u.GetQuotaSizePercentage() > 85
  255. }
  256. func (u *userQuotaUsage) IsQuotaFilesLow() bool {
  257. return u.GetQuotaFilesPercentage() > 85
  258. }
  259. func (u *userQuotaUsage) IsDiskQuotaLow() bool {
  260. return u.IsQuotaSizeLow() || u.IsQuotaFilesLow()
  261. }
  262. func (u *userQuotaUsage) GetTotalTransferQuota() string {
  263. total := u.UsedUploadDataTransfer + u.UsedDownloadDataTransfer
  264. if u.TotalDataTransfer > 0 {
  265. return fmt.Sprintf("%s/%s", util.ByteCountIEC(total), util.ByteCountIEC(u.TotalDataTransfer*1048576))
  266. }
  267. if total > 0 {
  268. return util.ByteCountIEC(total)
  269. }
  270. return ""
  271. }
  272. func (u *userQuotaUsage) GetUploadTransferQuota() string {
  273. if u.UploadDataTransfer > 0 {
  274. return fmt.Sprintf("%s/%s", util.ByteCountIEC(u.UsedUploadDataTransfer),
  275. util.ByteCountIEC(u.UploadDataTransfer*1048576))
  276. }
  277. if u.UsedUploadDataTransfer > 0 {
  278. return util.ByteCountIEC(u.UsedUploadDataTransfer)
  279. }
  280. return ""
  281. }
  282. func (u *userQuotaUsage) GetDownloadTransferQuota() string {
  283. if u.DownloadDataTransfer > 0 {
  284. return fmt.Sprintf("%s/%s", util.ByteCountIEC(u.UsedDownloadDataTransfer),
  285. util.ByteCountIEC(u.DownloadDataTransfer*1048576))
  286. }
  287. if u.UsedDownloadDataTransfer > 0 {
  288. return util.ByteCountIEC(u.UsedDownloadDataTransfer)
  289. }
  290. return ""
  291. }
  292. func (u *userQuotaUsage) GetTotalTransferQuotaPercentage() int {
  293. if u.TotalDataTransfer > 0 {
  294. return int(math.Round(100 * float64(u.UsedDownloadDataTransfer+u.UsedUploadDataTransfer) / float64(u.TotalDataTransfer*1048576)))
  295. }
  296. return 0
  297. }
  298. func (u *userQuotaUsage) GetUploadTransferQuotaPercentage() int {
  299. if u.UploadDataTransfer > 0 {
  300. return int(math.Round(100 * float64(u.UsedUploadDataTransfer) / float64(u.UploadDataTransfer*1048576)))
  301. }
  302. return 0
  303. }
  304. func (u *userQuotaUsage) GetDownloadTransferQuotaPercentage() int {
  305. if u.DownloadDataTransfer > 0 {
  306. return int(math.Round(100 * float64(u.UsedDownloadDataTransfer) / float64(u.DownloadDataTransfer*1048576)))
  307. }
  308. return 0
  309. }
  310. func (u *userQuotaUsage) IsTotalTransferQuotaLow() bool {
  311. if u.TotalDataTransfer > 0 {
  312. return u.GetTotalTransferQuotaPercentage() > 85
  313. }
  314. return false
  315. }
  316. func (u *userQuotaUsage) IsUploadTransferQuotaLow() bool {
  317. if u.UploadDataTransfer > 0 {
  318. return u.GetUploadTransferQuotaPercentage() > 85
  319. }
  320. return false
  321. }
  322. func (u *userQuotaUsage) IsDownloadTransferQuotaLow() bool {
  323. if u.DownloadDataTransfer > 0 {
  324. return u.GetDownloadTransferQuotaPercentage() > 85
  325. }
  326. return false
  327. }
  328. func (u *userQuotaUsage) IsTransferQuotaLow() bool {
  329. return u.IsTotalTransferQuotaLow() || u.IsUploadTransferQuotaLow() || u.IsDownloadTransferQuotaLow()
  330. }
  331. func (u *userQuotaUsage) IsQuotaLow() bool {
  332. return u.IsDiskQuotaLow() || u.IsTransferQuotaLow()
  333. }
  334. func newUserQuotaUsage(u *dataprovider.User) *userQuotaUsage {
  335. return &userQuotaUsage{
  336. QuotaSize: u.QuotaSize,
  337. QuotaFiles: u.QuotaFiles,
  338. UsedQuotaSize: u.UsedQuotaSize,
  339. UsedQuotaFiles: u.UsedQuotaFiles,
  340. TotalDataTransfer: u.TotalDataTransfer,
  341. UploadDataTransfer: u.UploadDataTransfer,
  342. DownloadDataTransfer: u.DownloadDataTransfer,
  343. UsedUploadDataTransfer: u.UsedUploadDataTransfer,
  344. UsedDownloadDataTransfer: u.UsedDownloadDataTransfer,
  345. }
  346. }
  347. func getFileObjectURL(baseDir, name, baseWebPath string) string {
  348. return fmt.Sprintf("%v?path=%v&_=%v", baseWebPath, url.QueryEscape(path.Join(baseDir, name)), time.Now().UTC().Unix())
  349. }
  350. func getFileObjectModTime(t time.Time) int64 {
  351. if isZeroTime(t) {
  352. return 0
  353. }
  354. return t.UnixMilli()
  355. }
  356. func loadClientTemplates(templatesPath string) {
  357. filesPaths := []string{
  358. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  359. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  360. filepath.Join(templatesPath, templateClientDir, templateClientFiles),
  361. }
  362. editFilePath := []string{
  363. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  364. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  365. filepath.Join(templatesPath, templateClientDir, templateClientEditFile),
  366. }
  367. sharesPaths := []string{
  368. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  369. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  370. filepath.Join(templatesPath, templateClientDir, templateClientShares),
  371. }
  372. sharePaths := []string{
  373. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  374. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  375. filepath.Join(templatesPath, templateClientDir, templateClientShare),
  376. }
  377. profilePaths := []string{
  378. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  379. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  380. filepath.Join(templatesPath, templateClientDir, templateClientProfile),
  381. }
  382. changePwdPaths := []string{
  383. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  384. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  385. filepath.Join(templatesPath, templateCommonDir, templateChangePwd),
  386. }
  387. loginPaths := []string{
  388. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  389. filepath.Join(templatesPath, templateCommonDir, templateCommonBaseLogin),
  390. filepath.Join(templatesPath, templateCommonDir, templateCommonLogin),
  391. }
  392. messagePaths := []string{
  393. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  394. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  395. filepath.Join(templatesPath, templateCommonDir, templateMessage),
  396. }
  397. mfaPaths := []string{
  398. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  399. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  400. filepath.Join(templatesPath, templateClientDir, templateClientMFA),
  401. }
  402. twoFactorPaths := []string{
  403. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  404. filepath.Join(templatesPath, templateCommonDir, templateCommonBaseLogin),
  405. filepath.Join(templatesPath, templateCommonDir, templateTwoFactor),
  406. }
  407. twoFactorRecoveryPaths := []string{
  408. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  409. filepath.Join(templatesPath, templateCommonDir, templateCommonBaseLogin),
  410. filepath.Join(templatesPath, templateCommonDir, templateTwoFactorRecovery),
  411. }
  412. forgotPwdPaths := []string{
  413. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  414. filepath.Join(templatesPath, templateCommonDir, templateCommonBaseLogin),
  415. filepath.Join(templatesPath, templateCommonDir, templateForgotPassword),
  416. }
  417. resetPwdPaths := []string{
  418. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  419. filepath.Join(templatesPath, templateCommonDir, templateCommonBaseLogin),
  420. filepath.Join(templatesPath, templateCommonDir, templateResetPassword),
  421. }
  422. viewPDFPaths := []string{
  423. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  424. filepath.Join(templatesPath, templateClientDir, templateClientViewPDF),
  425. }
  426. shareLoginPath := []string{
  427. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  428. filepath.Join(templatesPath, templateCommonDir, templateCommonBaseLogin),
  429. filepath.Join(templatesPath, templateClientDir, templateShareLogin),
  430. }
  431. shareUploadPath := []string{
  432. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  433. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  434. filepath.Join(templatesPath, templateClientDir, templateUploadToShare),
  435. }
  436. shareDownloadPath := []string{
  437. filepath.Join(templatesPath, templateCommonDir, templateCommonBase),
  438. filepath.Join(templatesPath, templateClientDir, templateClientBase),
  439. filepath.Join(templatesPath, templateClientDir, templateShareDownload),
  440. }
  441. filesTmpl := util.LoadTemplate(nil, filesPaths...)
  442. profileTmpl := util.LoadTemplate(nil, profilePaths...)
  443. changePwdTmpl := util.LoadTemplate(nil, changePwdPaths...)
  444. loginTmpl := util.LoadTemplate(nil, loginPaths...)
  445. messageTmpl := util.LoadTemplate(nil, messagePaths...)
  446. mfaTmpl := util.LoadTemplate(nil, mfaPaths...)
  447. twoFactorTmpl := util.LoadTemplate(nil, twoFactorPaths...)
  448. twoFactorRecoveryTmpl := util.LoadTemplate(nil, twoFactorRecoveryPaths...)
  449. editFileTmpl := util.LoadTemplate(nil, editFilePath...)
  450. shareLoginTmpl := util.LoadTemplate(nil, shareLoginPath...)
  451. sharesTmpl := util.LoadTemplate(nil, sharesPaths...)
  452. shareTmpl := util.LoadTemplate(nil, sharePaths...)
  453. forgotPwdTmpl := util.LoadTemplate(nil, forgotPwdPaths...)
  454. resetPwdTmpl := util.LoadTemplate(nil, resetPwdPaths...)
  455. viewPDFTmpl := util.LoadTemplate(nil, viewPDFPaths...)
  456. shareUploadTmpl := util.LoadTemplate(nil, shareUploadPath...)
  457. shareDownloadTmpl := util.LoadTemplate(nil, shareDownloadPath...)
  458. clientTemplates[templateClientFiles] = filesTmpl
  459. clientTemplates[templateClientProfile] = profileTmpl
  460. clientTemplates[templateChangePwd] = changePwdTmpl
  461. clientTemplates[templateCommonLogin] = loginTmpl
  462. clientTemplates[templateMessage] = messageTmpl
  463. clientTemplates[templateClientMFA] = mfaTmpl
  464. clientTemplates[templateTwoFactor] = twoFactorTmpl
  465. clientTemplates[templateTwoFactorRecovery] = twoFactorRecoveryTmpl
  466. clientTemplates[templateClientEditFile] = editFileTmpl
  467. clientTemplates[templateClientShares] = sharesTmpl
  468. clientTemplates[templateClientShare] = shareTmpl
  469. clientTemplates[templateForgotPassword] = forgotPwdTmpl
  470. clientTemplates[templateResetPassword] = resetPwdTmpl
  471. clientTemplates[templateClientViewPDF] = viewPDFTmpl
  472. clientTemplates[templateShareLogin] = shareLoginTmpl
  473. clientTemplates[templateUploadToShare] = shareUploadTmpl
  474. clientTemplates[templateShareDownload] = shareDownloadTmpl
  475. }
  476. func (s *httpdServer) getBaseClientPageData(title, currentURL string, w http.ResponseWriter, r *http.Request) baseClientPage {
  477. var csrfToken string
  478. if currentURL != "" {
  479. csrfToken = createCSRFToken(w, r, s.csrfTokenAuth, "", webBaseClientPath)
  480. }
  481. data := baseClientPage{
  482. commonBasePage: getCommonBasePage(r),
  483. Title: title,
  484. CurrentURL: currentURL,
  485. FilesURL: webClientFilesPath,
  486. SharesURL: webClientSharesPath,
  487. ShareURL: webClientSharePath,
  488. ProfileURL: webClientProfilePath,
  489. PingURL: webClientPingPath,
  490. ChangePwdURL: webChangeClientPwdPath,
  491. LogoutURL: webClientLogoutPath,
  492. EditURL: webClientEditFilePath,
  493. MFAURL: webClientMFAPath,
  494. CSRFToken: csrfToken,
  495. LoggedUser: getUserFromToken(r),
  496. IsLoggedToShare: false,
  497. Branding: s.binding.webClientBranding(),
  498. }
  499. if !strings.HasPrefix(r.RequestURI, webClientPubSharesPath) {
  500. data.LoginURL = webClientLoginPath
  501. }
  502. return data
  503. }
  504. func (s *httpdServer) renderClientForgotPwdPage(w http.ResponseWriter, r *http.Request, err *util.I18nError) {
  505. data := forgotPwdPage{
  506. commonBasePage: getCommonBasePage(r),
  507. CurrentURL: webClientForgotPwdPath,
  508. Error: err,
  509. CSRFToken: createCSRFToken(w, r, s.csrfTokenAuth, xid.New().String(), webBaseClientPath),
  510. LoginURL: webClientLoginPath,
  511. Title: util.I18nForgotPwdTitle,
  512. Branding: s.binding.webClientBranding(),
  513. }
  514. renderClientTemplate(w, templateForgotPassword, data)
  515. }
  516. func (s *httpdServer) renderClientResetPwdPage(w http.ResponseWriter, r *http.Request, err *util.I18nError) {
  517. data := resetPwdPage{
  518. commonBasePage: getCommonBasePage(r),
  519. CurrentURL: webClientResetPwdPath,
  520. Error: err,
  521. CSRFToken: createCSRFToken(w, r, s.csrfTokenAuth, "", webBaseClientPath),
  522. LoginURL: webClientLoginPath,
  523. Title: util.I18nResetPwdTitle,
  524. Branding: s.binding.webClientBranding(),
  525. }
  526. renderClientTemplate(w, templateResetPassword, data)
  527. }
  528. func (s *httpdServer) renderShareLoginPage(w http.ResponseWriter, r *http.Request, err *util.I18nError) {
  529. data := shareLoginPage{
  530. commonBasePage: getCommonBasePage(r),
  531. Title: util.I18nShareLoginTitle,
  532. CurrentURL: r.RequestURI,
  533. Error: err,
  534. CSRFToken: createCSRFToken(w, r, s.csrfTokenAuth, xid.New().String(), webBaseClientPath),
  535. Branding: s.binding.webClientBranding(),
  536. }
  537. renderClientTemplate(w, templateShareLogin, data)
  538. }
  539. func renderClientTemplate(w http.ResponseWriter, tmplName string, data any) {
  540. err := clientTemplates[tmplName].ExecuteTemplate(w, tmplName, data)
  541. if err != nil {
  542. http.Error(w, err.Error(), http.StatusInternalServerError)
  543. }
  544. }
  545. func (s *httpdServer) renderClientMessagePage(w http.ResponseWriter, r *http.Request, title string, statusCode int, err error, message string) {
  546. data := clientMessagePage{
  547. baseClientPage: s.getBaseClientPageData(title, "", w, r),
  548. Error: getI18nError(err),
  549. Success: message,
  550. }
  551. w.WriteHeader(statusCode)
  552. renderClientTemplate(w, templateMessage, data)
  553. }
  554. func (s *httpdServer) renderClientInternalServerErrorPage(w http.ResponseWriter, r *http.Request, err error) {
  555. s.renderClientMessagePage(w, r, util.I18nError500Title, http.StatusInternalServerError,
  556. util.NewI18nError(err, util.I18nError500Message), "")
  557. }
  558. func (s *httpdServer) renderClientBadRequestPage(w http.ResponseWriter, r *http.Request, err error) {
  559. s.renderClientMessagePage(w, r, util.I18nError400Title, http.StatusBadRequest,
  560. util.NewI18nError(err, util.I18nError400Message), "")
  561. }
  562. func (s *httpdServer) renderClientForbiddenPage(w http.ResponseWriter, r *http.Request, err error) {
  563. s.renderClientMessagePage(w, r, util.I18nError403Title, http.StatusForbidden,
  564. util.NewI18nError(err, util.I18nError403Message), "")
  565. }
  566. func (s *httpdServer) renderClientNotFoundPage(w http.ResponseWriter, r *http.Request, err error) {
  567. s.renderClientMessagePage(w, r, util.I18nError404Title, http.StatusNotFound,
  568. util.NewI18nError(err, util.I18nError404Message), "")
  569. }
  570. func (s *httpdServer) renderClientTwoFactorPage(w http.ResponseWriter, r *http.Request, err *util.I18nError) {
  571. data := twoFactorPage{
  572. commonBasePage: getCommonBasePage(r),
  573. Title: pageTwoFactorTitle,
  574. CurrentURL: webClientTwoFactorPath,
  575. Error: err,
  576. CSRFToken: createCSRFToken(w, r, s.csrfTokenAuth, "", webBaseClientPath),
  577. RecoveryURL: webClientTwoFactorRecoveryPath,
  578. Branding: s.binding.webClientBranding(),
  579. }
  580. if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
  581. data.CurrentURL += "?next=" + url.QueryEscape(next)
  582. }
  583. renderClientTemplate(w, templateTwoFactor, data)
  584. }
  585. func (s *httpdServer) renderClientTwoFactorRecoveryPage(w http.ResponseWriter, r *http.Request, err *util.I18nError) {
  586. data := twoFactorPage{
  587. commonBasePage: getCommonBasePage(r),
  588. Title: pageTwoFactorRecoveryTitle,
  589. CurrentURL: webClientTwoFactorRecoveryPath,
  590. Error: err,
  591. CSRFToken: createCSRFToken(w, r, s.csrfTokenAuth, "", webBaseClientPath),
  592. Branding: s.binding.webClientBranding(),
  593. }
  594. renderClientTemplate(w, templateTwoFactorRecovery, data)
  595. }
  596. func (s *httpdServer) renderClientMFAPage(w http.ResponseWriter, r *http.Request) {
  597. data := clientMFAPage{
  598. baseClientPage: s.getBaseClientPageData(util.I18n2FATitle, webClientMFAPath, w, r),
  599. TOTPConfigs: mfa.GetAvailableTOTPConfigNames(),
  600. GenerateTOTPURL: webClientTOTPGeneratePath,
  601. ValidateTOTPURL: webClientTOTPValidatePath,
  602. SaveTOTPURL: webClientTOTPSavePath,
  603. RecCodesURL: webClientRecoveryCodesPath,
  604. Protocols: dataprovider.MFAProtocols,
  605. }
  606. user, err := dataprovider.GetUserWithGroupSettings(data.LoggedUser.Username, "")
  607. if err != nil {
  608. s.renderClientInternalServerErrorPage(w, r, err)
  609. return
  610. }
  611. data.TOTPConfig = user.Filters.TOTPConfig
  612. data.RequiredProtocols = user.Filters.TwoFactorAuthProtocols
  613. renderClientTemplate(w, templateClientMFA, data)
  614. }
  615. func (s *httpdServer) renderEditFilePage(w http.ResponseWriter, r *http.Request, fileName, fileData string, readOnly bool) {
  616. title := util.I18nViewFileTitle
  617. if !readOnly {
  618. title = util.I18nEditFileTitle
  619. }
  620. data := editFilePage{
  621. baseClientPage: s.getBaseClientPageData(title, webClientEditFilePath, w, r),
  622. Path: fileName,
  623. Name: path.Base(fileName),
  624. CurrentDir: path.Dir(fileName),
  625. FileURL: webClientFilePath,
  626. ReadOnly: readOnly,
  627. Data: fileData,
  628. }
  629. renderClientTemplate(w, templateClientEditFile, data)
  630. }
  631. func (s *httpdServer) renderAddUpdateSharePage(w http.ResponseWriter, r *http.Request, share *dataprovider.Share,
  632. err *util.I18nError, isAdd bool) {
  633. currentURL := webClientSharePath
  634. title := util.I18nShareAddTitle
  635. if !isAdd {
  636. currentURL = fmt.Sprintf("%v/%v", webClientSharePath, url.PathEscape(share.ShareID))
  637. title = util.I18nShareUpdateTitle
  638. }
  639. data := clientSharePage{
  640. baseClientPage: s.getBaseClientPageData(title, currentURL, w, r),
  641. Share: share,
  642. Error: err,
  643. IsAdd: isAdd,
  644. }
  645. renderClientTemplate(w, templateClientShare, data)
  646. }
  647. func getDirMapping(dirName, baseWebPath string) []dirMapping {
  648. paths := []dirMapping{}
  649. if dirName != "/" {
  650. paths = append(paths, dirMapping{
  651. DirName: path.Base(dirName),
  652. Href: getFileObjectURL("/", dirName, baseWebPath),
  653. })
  654. for {
  655. dirName = path.Dir(dirName)
  656. if dirName == "/" || dirName == "." {
  657. break
  658. }
  659. paths = append([]dirMapping{{
  660. DirName: path.Base(dirName),
  661. Href: getFileObjectURL("/", dirName, baseWebPath)},
  662. }, paths...)
  663. }
  664. }
  665. return paths
  666. }
  667. func (s *httpdServer) renderSharedFilesPage(w http.ResponseWriter, r *http.Request, dirName string,
  668. err *util.I18nError, share dataprovider.Share,
  669. ) {
  670. currentURL := path.Join(webClientPubSharesPath, share.ShareID, "browse")
  671. baseData := s.getBaseClientPageData(util.I18nSharedFilesTitle, currentURL, w, r)
  672. baseData.FilesURL = currentURL
  673. baseSharePath := path.Join(webClientPubSharesPath, share.ShareID)
  674. baseData.LogoutURL = path.Join(webClientPubSharesPath, share.ShareID, "logout")
  675. baseData.IsLoggedToShare = share.Password != ""
  676. data := filesPage{
  677. baseClientPage: baseData,
  678. Error: err,
  679. CurrentDir: url.QueryEscape(dirName),
  680. DownloadURL: path.Join(baseSharePath, "partial"),
  681. // dirName must be escaped because the router expects the full path as single argument
  682. ShareUploadBaseURL: path.Join(baseSharePath, url.PathEscape(dirName)),
  683. ViewPDFURL: path.Join(baseSharePath, "viewpdf"),
  684. DirsURL: path.Join(baseSharePath, "dirs"),
  685. FileURL: "",
  686. FileActionsURL: "",
  687. CheckExistURL: path.Join(baseSharePath, "browse", "exist"),
  688. TasksURL: "",
  689. CanAddFiles: share.Scope == dataprovider.ShareScopeReadWrite,
  690. CanCreateDirs: false,
  691. CanRename: false,
  692. CanDelete: false,
  693. CanDownload: share.Scope != dataprovider.ShareScopeWrite,
  694. CanShare: false,
  695. CanCopy: false,
  696. Paths: getDirMapping(dirName, currentURL),
  697. QuotaUsage: newUserQuotaUsage(&dataprovider.User{}),
  698. }
  699. renderClientTemplate(w, templateClientFiles, data)
  700. }
  701. func (s *httpdServer) renderShareDownloadPage(w http.ResponseWriter, r *http.Request, share *dataprovider.Share,
  702. downloadLink string,
  703. ) {
  704. data := shareDownloadPage{
  705. baseClientPage: s.getBaseClientPageData(util.I18nShareDownloadTitle, "", w, r),
  706. DownloadLink: downloadLink,
  707. }
  708. data.LogoutURL = ""
  709. if share.Password != "" {
  710. data.LogoutURL = path.Join(webClientPubSharesPath, share.ShareID, "logout")
  711. }
  712. renderClientTemplate(w, templateShareDownload, data)
  713. }
  714. func (s *httpdServer) renderUploadToSharePage(w http.ResponseWriter, r *http.Request, share *dataprovider.Share) {
  715. currentURL := path.Join(webClientPubSharesPath, share.ShareID, "upload")
  716. data := shareUploadPage{
  717. baseClientPage: s.getBaseClientPageData(util.I18nShareUploadTitle, currentURL, w, r),
  718. Share: share,
  719. UploadBasePath: path.Join(webClientPubSharesPath, share.ShareID),
  720. }
  721. data.LogoutURL = ""
  722. if share.Password != "" {
  723. data.LogoutURL = path.Join(webClientPubSharesPath, share.ShareID, "logout")
  724. }
  725. renderClientTemplate(w, templateUploadToShare, data)
  726. }
  727. func (s *httpdServer) renderFilesPage(w http.ResponseWriter, r *http.Request, dirName string,
  728. err *util.I18nError, user *dataprovider.User) {
  729. data := filesPage{
  730. baseClientPage: s.getBaseClientPageData(util.I18nFilesTitle, webClientFilesPath, w, r),
  731. Error: err,
  732. CurrentDir: url.QueryEscape(dirName),
  733. DownloadURL: webClientDownloadZipPath,
  734. ViewPDFURL: webClientViewPDFPath,
  735. DirsURL: webClientDirsPath,
  736. FileURL: webClientFilePath,
  737. FileActionsURL: webClientFileActionsPath,
  738. CheckExistURL: webClientExistPath,
  739. TasksURL: webClientTasksPath,
  740. CanAddFiles: user.CanAddFilesFromWeb(dirName),
  741. CanCreateDirs: user.CanAddDirsFromWeb(dirName),
  742. CanRename: user.CanRenameFromWeb(dirName, dirName),
  743. CanDelete: user.CanDeleteFromWeb(dirName),
  744. CanDownload: user.HasPerm(dataprovider.PermDownload, dirName),
  745. CanShare: user.CanManageShares(),
  746. CanCopy: user.CanCopyFromWeb(dirName, dirName),
  747. ShareUploadBaseURL: "",
  748. Paths: getDirMapping(dirName, webClientFilesPath),
  749. QuotaUsage: newUserQuotaUsage(user),
  750. }
  751. renderClientTemplate(w, templateClientFiles, data)
  752. }
  753. func (s *httpdServer) renderClientProfilePage(w http.ResponseWriter, r *http.Request, err *util.I18nError) {
  754. data := clientProfilePage{
  755. baseClientPage: s.getBaseClientPageData(util.I18nProfileTitle, webClientProfilePath, w, r),
  756. Error: err,
  757. }
  758. user, userMerged, errUser := dataprovider.GetUserVariants(data.LoggedUser.Username, "")
  759. if errUser != nil {
  760. s.renderClientInternalServerErrorPage(w, r, errUser)
  761. return
  762. }
  763. data.PublicKeys = user.PublicKeys
  764. data.TLSCerts = user.Filters.TLSCerts
  765. data.AllowAPIKeyAuth = user.Filters.AllowAPIKeyAuth
  766. data.Email = user.Email
  767. data.Description = user.Description
  768. data.CanSubmit = userMerged.CanUpdateProfile()
  769. renderClientTemplate(w, templateClientProfile, data)
  770. }
  771. func (s *httpdServer) renderClientChangePasswordPage(w http.ResponseWriter, r *http.Request, err *util.I18nError) {
  772. data := changeClientPasswordPage{
  773. baseClientPage: s.getBaseClientPageData(util.I18nChangePwdTitle, webChangeClientPwdPath, w, r),
  774. Error: err,
  775. }
  776. renderClientTemplate(w, templateChangePwd, data)
  777. }
  778. func (s *httpdServer) handleWebClientDownloadZip(w http.ResponseWriter, r *http.Request) {
  779. r.Body = http.MaxBytesReader(w, r.Body, maxMultipartMem)
  780. claims, err := getTokenClaims(r)
  781. if err != nil || claims.Username == "" {
  782. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  783. return
  784. }
  785. if err := r.ParseForm(); err != nil {
  786. s.renderClientBadRequestPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  787. return
  788. }
  789. if err := verifyCSRFToken(r, s.csrfTokenAuth); err != nil {
  790. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  791. return
  792. }
  793. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  794. if err != nil {
  795. s.renderClientMessagePage(w, r, util.I18nError500Title, getRespStatus(err),
  796. util.NewI18nError(err, util.I18nErrorGetUser), "")
  797. return
  798. }
  799. connID := xid.New().String()
  800. protocol := getProtocolFromRequest(r)
  801. connectionID := fmt.Sprintf("%v_%v", protocol, connID)
  802. if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
  803. s.renderClientForbiddenPage(w, r, err)
  804. return
  805. }
  806. connection := &Connection{
  807. BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
  808. r.RemoteAddr, user),
  809. request: r,
  810. }
  811. if err = common.Connections.Add(connection); err != nil {
  812. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  813. util.NewI18nError(err, util.I18nError429Message), "")
  814. return
  815. }
  816. defer common.Connections.Remove(connection.GetID())
  817. name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
  818. files := r.Form.Get("files")
  819. var filesList []string
  820. err = json.Unmarshal(util.StringToBytes(files), &filesList)
  821. if err != nil {
  822. s.renderClientBadRequestPage(w, r, err)
  823. return
  824. }
  825. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"",
  826. getCompressedFileName(connection.GetUsername(), filesList)))
  827. renderCompressedFiles(w, connection, name, filesList, nil)
  828. }
  829. func (s *httpdServer) handleClientSharePartialDownload(w http.ResponseWriter, r *http.Request) {
  830. r.Body = http.MaxBytesReader(w, r.Body, maxMultipartMem)
  831. if err := r.ParseForm(); err != nil {
  832. s.renderClientBadRequestPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  833. return
  834. }
  835. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
  836. share, connection, err := s.checkPublicShare(w, r, validScopes)
  837. if err != nil {
  838. return
  839. }
  840. if err := validateBrowsableShare(share, connection); err != nil {
  841. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, getRespStatus(err), err, "")
  842. return
  843. }
  844. name, err := getBrowsableSharedPath(share.Paths[0], r)
  845. if err != nil {
  846. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, getRespStatus(err), err, "")
  847. return
  848. }
  849. if err = common.Connections.Add(connection); err != nil {
  850. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  851. util.NewI18nError(err, util.I18nError429Message), "")
  852. return
  853. }
  854. defer common.Connections.Remove(connection.GetID())
  855. transferQuota := connection.GetTransferQuota()
  856. if !transferQuota.HasDownloadSpace() {
  857. err = util.NewI18nError(connection.GetReadQuotaExceededError(), util.I18nErrorQuotaRead)
  858. connection.Log(logger.LevelInfo, "denying share read due to quota limits")
  859. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, getMappedStatusCode(err), err, "")
  860. return
  861. }
  862. files := r.Form.Get("files")
  863. var filesList []string
  864. err = json.Unmarshal(util.StringToBytes(files), &filesList)
  865. if err != nil {
  866. s.renderClientBadRequestPage(w, r, err)
  867. return
  868. }
  869. dataprovider.UpdateShareLastUse(&share, 1) //nolint:errcheck
  870. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"",
  871. getCompressedFileName(fmt.Sprintf("share-%s", share.Name), filesList)))
  872. renderCompressedFiles(w, connection, name, filesList, &share)
  873. }
  874. func (s *httpdServer) handleShareGetDirContents(w http.ResponseWriter, r *http.Request) {
  875. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  876. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
  877. share, connection, err := s.checkPublicShare(w, r, validScopes)
  878. if err != nil {
  879. return
  880. }
  881. if err := validateBrowsableShare(share, connection); err != nil {
  882. sendAPIResponse(w, r, err, getI18NErrorString(err, util.I18nError500Message), getRespStatus(err))
  883. return
  884. }
  885. name, err := getBrowsableSharedPath(share.Paths[0], r)
  886. if err != nil {
  887. sendAPIResponse(w, r, err, getI18NErrorString(err, util.I18nError500Message), getRespStatus(err))
  888. return
  889. }
  890. if err = common.Connections.Add(connection); err != nil {
  891. sendAPIResponse(w, r, err, getI18NErrorString(err, util.I18nError429Message), http.StatusTooManyRequests)
  892. return
  893. }
  894. defer common.Connections.Remove(connection.GetID())
  895. lister, err := connection.ReadDir(name)
  896. if err != nil {
  897. sendAPIResponse(w, r, err, getI18NErrorString(err, util.I18nErrorDirListGeneric), getMappedStatusCode(err))
  898. return
  899. }
  900. defer lister.Close()
  901. dataGetter := func(limit, _ int) ([]byte, int, error) {
  902. contents, err := lister.Next(limit)
  903. if errors.Is(err, io.EOF) {
  904. err = nil
  905. }
  906. if err != nil {
  907. return nil, 0, err
  908. }
  909. results := make([]map[string]any, 0, len(contents))
  910. for _, info := range contents {
  911. if !info.Mode().IsDir() && !info.Mode().IsRegular() {
  912. continue
  913. }
  914. res := make(map[string]any)
  915. if info.IsDir() {
  916. res["type"] = "1"
  917. res["size"] = ""
  918. } else {
  919. res["type"] = "2"
  920. res["size"] = info.Size()
  921. }
  922. res["meta"] = fmt.Sprintf("%v_%v", res["type"], info.Name())
  923. res["name"] = info.Name()
  924. res["url"] = getFileObjectURL(share.GetRelativePath(name), info.Name(),
  925. path.Join(webClientPubSharesPath, share.ShareID, "browse"))
  926. res["last_modified"] = getFileObjectModTime(info.ModTime())
  927. results = append(results, res)
  928. }
  929. data, err := json.Marshal(results)
  930. count := limit
  931. if len(results) == 0 {
  932. count = 0
  933. }
  934. return data, count, err
  935. }
  936. streamJSONArray(w, defaultQueryLimit, dataGetter)
  937. }
  938. func (s *httpdServer) handleClientUploadToShare(w http.ResponseWriter, r *http.Request) {
  939. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  940. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeWrite, dataprovider.ShareScopeReadWrite}
  941. share, _, err := s.checkPublicShare(w, r, validScopes)
  942. if err != nil {
  943. return
  944. }
  945. if share.Scope == dataprovider.ShareScopeReadWrite {
  946. http.Redirect(w, r, path.Join(webClientPubSharesPath, share.ShareID, "browse"), http.StatusFound)
  947. return
  948. }
  949. s.renderUploadToSharePage(w, r, &share)
  950. }
  951. func (s *httpdServer) handleShareGetFiles(w http.ResponseWriter, r *http.Request) {
  952. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  953. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
  954. share, connection, err := s.checkPublicShare(w, r, validScopes)
  955. if err != nil {
  956. return
  957. }
  958. if err := validateBrowsableShare(share, connection); err != nil {
  959. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, getRespStatus(err), err, "")
  960. return
  961. }
  962. name, err := getBrowsableSharedPath(share.Paths[0], r)
  963. if err != nil {
  964. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, getRespStatus(err), err, "")
  965. return
  966. }
  967. if err = common.Connections.Add(connection); err != nil {
  968. s.renderSharedFilesPage(w, r, path.Dir(share.GetRelativePath(name)),
  969. util.NewI18nError(err, util.I18nError429Message), share)
  970. return
  971. }
  972. defer common.Connections.Remove(connection.GetID())
  973. var info os.FileInfo
  974. if name == "/" {
  975. info = vfs.NewFileInfo(name, true, 0, time.Unix(0, 0), false)
  976. } else {
  977. info, err = connection.Stat(name, 1)
  978. }
  979. if err != nil {
  980. s.renderSharedFilesPage(w, r, path.Dir(share.GetRelativePath(name)),
  981. util.NewI18nError(err, i18nFsMsg(getRespStatus(err))), share)
  982. return
  983. }
  984. if info.IsDir() {
  985. s.renderSharedFilesPage(w, r, share.GetRelativePath(name), nil, share)
  986. return
  987. }
  988. dataprovider.UpdateShareLastUse(&share, 1) //nolint:errcheck
  989. if status, err := downloadFile(w, r, connection, name, info, false, &share); err != nil {
  990. dataprovider.UpdateShareLastUse(&share, -1) //nolint:errcheck
  991. if status > 0 {
  992. s.renderSharedFilesPage(w, r, path.Dir(share.GetRelativePath(name)),
  993. util.NewI18nError(err, i18nFsMsg(getRespStatus(err))), share)
  994. }
  995. }
  996. }
  997. func (s *httpdServer) handleShareViewPDF(w http.ResponseWriter, r *http.Request) {
  998. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  999. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
  1000. share, _, err := s.checkPublicShare(w, r, validScopes)
  1001. if err != nil {
  1002. return
  1003. }
  1004. name := util.CleanPath(r.URL.Query().Get("path"))
  1005. data := viewPDFPage{
  1006. commonBasePage: getCommonBasePage(r),
  1007. Title: path.Base(name),
  1008. URL: fmt.Sprintf("%s?path=%s&_=%d", path.Join(webClientPubSharesPath, share.ShareID, "getpdf"),
  1009. url.QueryEscape(name), time.Now().UTC().Unix()),
  1010. Branding: s.binding.webClientBranding(),
  1011. }
  1012. renderClientTemplate(w, templateClientViewPDF, data)
  1013. }
  1014. func (s *httpdServer) handleShareGetPDF(w http.ResponseWriter, r *http.Request) {
  1015. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1016. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead, dataprovider.ShareScopeReadWrite}
  1017. share, connection, err := s.checkPublicShare(w, r, validScopes)
  1018. if err != nil {
  1019. return
  1020. }
  1021. if err := validateBrowsableShare(share, connection); err != nil {
  1022. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, getRespStatus(err), err, "")
  1023. return
  1024. }
  1025. name, err := getBrowsableSharedPath(share.Paths[0], r)
  1026. if err != nil {
  1027. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, getRespStatus(err), err, "")
  1028. return
  1029. }
  1030. if err = common.Connections.Add(connection); err != nil {
  1031. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1032. util.NewI18nError(err, util.I18nError429Message), "")
  1033. return
  1034. }
  1035. defer common.Connections.Remove(connection.GetID())
  1036. info, err := connection.Stat(name, 1)
  1037. if err != nil {
  1038. status := getRespStatus(err)
  1039. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, status,
  1040. util.NewI18nError(err, i18nFsMsg(status)), "")
  1041. return
  1042. }
  1043. if info.IsDir() {
  1044. s.renderClientBadRequestPage(w, r, util.NewI18nError(fmt.Errorf("%q is not a file", name), util.I18nErrorPDFMessage))
  1045. return
  1046. }
  1047. connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
  1048. if err := s.ensurePDF(w, r, name, connection); err != nil {
  1049. return
  1050. }
  1051. dataprovider.UpdateShareLastUse(&share, 1) //nolint:errcheck
  1052. if _, err := downloadFile(w, r, connection, name, info, true, &share); err != nil {
  1053. dataprovider.UpdateShareLastUse(&share, -1) //nolint:errcheck
  1054. }
  1055. }
  1056. func (s *httpdServer) handleClientGetDirContents(w http.ResponseWriter, r *http.Request) {
  1057. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1058. claims, err := getTokenClaims(r)
  1059. if err != nil || claims.Username == "" {
  1060. sendAPIResponse(w, r, nil, util.I18nErrorDirList403, http.StatusForbidden)
  1061. return
  1062. }
  1063. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  1064. if err != nil {
  1065. sendAPIResponse(w, r, nil, util.I18nErrorDirListUser, getRespStatus(err))
  1066. return
  1067. }
  1068. connID := xid.New().String()
  1069. protocol := getProtocolFromRequest(r)
  1070. connectionID := fmt.Sprintf("%s_%s", protocol, connID)
  1071. if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
  1072. sendAPIResponse(w, r, err, getI18NErrorString(err, util.I18nErrorDirList403), http.StatusForbidden)
  1073. return
  1074. }
  1075. connection := &Connection{
  1076. BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
  1077. r.RemoteAddr, user),
  1078. request: r,
  1079. }
  1080. if err = common.Connections.Add(connection); err != nil {
  1081. sendAPIResponse(w, r, err, util.I18nErrorDirList429, http.StatusTooManyRequests)
  1082. return
  1083. }
  1084. defer common.Connections.Remove(connection.GetID())
  1085. name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
  1086. lister, err := connection.ReadDir(name)
  1087. if err != nil {
  1088. statusCode := getMappedStatusCode(err)
  1089. sendAPIResponse(w, r, err, i18nListDirMsg(statusCode), statusCode)
  1090. return
  1091. }
  1092. defer lister.Close()
  1093. dirTree := r.URL.Query().Get("dirtree") == "1"
  1094. dataGetter := func(limit, _ int) ([]byte, int, error) {
  1095. contents, err := lister.Next(limit)
  1096. if errors.Is(err, io.EOF) {
  1097. err = nil
  1098. }
  1099. if err != nil {
  1100. return nil, 0, err
  1101. }
  1102. results := make([]map[string]any, 0, len(contents))
  1103. for _, info := range contents {
  1104. res := make(map[string]any)
  1105. res["url"] = getFileObjectURL(name, info.Name(), webClientFilesPath)
  1106. if info.IsDir() {
  1107. res["type"] = "1"
  1108. res["size"] = ""
  1109. res["dir_path"] = url.QueryEscape(path.Join(name, info.Name()))
  1110. } else {
  1111. if dirTree {
  1112. continue
  1113. }
  1114. res["type"] = "2"
  1115. if info.Mode()&os.ModeSymlink != 0 {
  1116. res["size"] = ""
  1117. } else {
  1118. res["size"] = info.Size()
  1119. if info.Size() < httpdMaxEditFileSize {
  1120. res["edit_url"] = strings.Replace(res["url"].(string), webClientFilesPath, webClientEditFilePath, 1)
  1121. }
  1122. }
  1123. }
  1124. res["meta"] = fmt.Sprintf("%v_%v", res["type"], info.Name())
  1125. res["name"] = info.Name()
  1126. res["last_modified"] = getFileObjectModTime(info.ModTime())
  1127. results = append(results, res)
  1128. }
  1129. data, err := json.Marshal(results)
  1130. count := limit
  1131. if len(results) == 0 {
  1132. count = 0
  1133. }
  1134. return data, count, err
  1135. }
  1136. streamJSONArray(w, defaultQueryLimit, dataGetter)
  1137. }
  1138. func (s *httpdServer) handleClientGetFiles(w http.ResponseWriter, r *http.Request) {
  1139. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1140. claims, err := getTokenClaims(r)
  1141. if err != nil || claims.Username == "" {
  1142. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1143. return
  1144. }
  1145. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  1146. if err != nil {
  1147. s.renderClientMessagePage(w, r, util.I18nError500Title, getRespStatus(err),
  1148. util.NewI18nError(err, util.I18nErrorGetUser), "")
  1149. return
  1150. }
  1151. connID := xid.New().String()
  1152. protocol := getProtocolFromRequest(r)
  1153. connectionID := fmt.Sprintf("%v_%v", protocol, connID)
  1154. if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
  1155. s.renderClientForbiddenPage(w, r, err)
  1156. return
  1157. }
  1158. connection := &Connection{
  1159. BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
  1160. r.RemoteAddr, user),
  1161. request: r,
  1162. }
  1163. if err = common.Connections.Add(connection); err != nil {
  1164. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1165. util.NewI18nError(err, util.I18nError429Message), "")
  1166. return
  1167. }
  1168. defer common.Connections.Remove(connection.GetID())
  1169. name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
  1170. var info os.FileInfo
  1171. if name == "/" {
  1172. info = vfs.NewFileInfo(name, true, 0, time.Unix(0, 0), false)
  1173. } else {
  1174. info, err = connection.Stat(name, 0)
  1175. }
  1176. if err != nil {
  1177. s.renderFilesPage(w, r, path.Dir(name), util.NewI18nError(err, i18nFsMsg(getRespStatus(err))), &user)
  1178. return
  1179. }
  1180. if info.IsDir() {
  1181. s.renderFilesPage(w, r, name, nil, &user)
  1182. return
  1183. }
  1184. if status, err := downloadFile(w, r, connection, name, info, false, nil); err != nil && status != 0 {
  1185. if status > 0 {
  1186. if status == http.StatusRequestedRangeNotSatisfiable {
  1187. s.renderClientMessagePage(w, r, util.I18nError416Title, status,
  1188. util.NewI18nError(err, util.I18nError416Message), "")
  1189. return
  1190. }
  1191. s.renderFilesPage(w, r, path.Dir(name), util.NewI18nError(err, i18nFsMsg(status)), &user)
  1192. }
  1193. }
  1194. }
  1195. func (s *httpdServer) handleClientEditFile(w http.ResponseWriter, r *http.Request) {
  1196. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1197. claims, err := getTokenClaims(r)
  1198. if err != nil || claims.Username == "" {
  1199. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1200. return
  1201. }
  1202. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  1203. if err != nil {
  1204. s.renderClientMessagePage(w, r, util.I18nError500Title, getRespStatus(err),
  1205. util.NewI18nError(err, util.I18nErrorGetUser), "")
  1206. return
  1207. }
  1208. connID := xid.New().String()
  1209. protocol := getProtocolFromRequest(r)
  1210. connectionID := fmt.Sprintf("%v_%v", protocol, connID)
  1211. if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
  1212. s.renderClientForbiddenPage(w, r, err)
  1213. return
  1214. }
  1215. connection := &Connection{
  1216. BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
  1217. r.RemoteAddr, user),
  1218. request: r,
  1219. }
  1220. if err = common.Connections.Add(connection); err != nil {
  1221. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1222. util.NewI18nError(err, util.I18nError429Message), "")
  1223. return
  1224. }
  1225. defer common.Connections.Remove(connection.GetID())
  1226. name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
  1227. info, err := connection.Stat(name, 0)
  1228. if err != nil {
  1229. status := getRespStatus(err)
  1230. s.renderClientMessagePage(w, r, util.I18nErrorEditorTitle, status, util.NewI18nError(err, i18nFsMsg(status)), "")
  1231. return
  1232. }
  1233. if info.IsDir() {
  1234. s.renderClientMessagePage(w, r, util.I18nErrorEditorTitle, http.StatusBadRequest,
  1235. util.NewI18nError(
  1236. util.NewValidationError(fmt.Sprintf("The path %q does not point to a file", name)),
  1237. util.I18nErrorEditDir,
  1238. ), "")
  1239. return
  1240. }
  1241. if info.Size() > httpdMaxEditFileSize {
  1242. s.renderClientMessagePage(w, r, util.I18nErrorEditorTitle, http.StatusBadRequest,
  1243. util.NewI18nError(
  1244. util.NewValidationError(fmt.Sprintf("The file size %v for %q exceeds the maximum allowed size",
  1245. util.ByteCountIEC(info.Size()), name)),
  1246. util.I18nErrorEditSize,
  1247. ), "")
  1248. return
  1249. }
  1250. connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
  1251. reader, err := connection.getFileReader(name, 0, r.Method)
  1252. if err != nil {
  1253. s.renderClientMessagePage(w, r, util.I18nErrorEditorTitle, getRespStatus(err),
  1254. util.NewI18nError(err, util.I18nError500Message), "")
  1255. return
  1256. }
  1257. defer reader.Close()
  1258. var b bytes.Buffer
  1259. _, err = io.Copy(&b, reader)
  1260. if err != nil {
  1261. s.renderClientMessagePage(w, r, util.I18nErrorEditorTitle, getRespStatus(err),
  1262. util.NewI18nError(err, util.I18nError500Message), "")
  1263. return
  1264. }
  1265. s.renderEditFilePage(w, r, name, b.String(), !user.CanAddFilesFromWeb(path.Dir(name)))
  1266. }
  1267. func (s *httpdServer) handleClientAddShareGet(w http.ResponseWriter, r *http.Request) {
  1268. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1269. claims, err := getTokenClaims(r)
  1270. if err != nil || claims.Username == "" {
  1271. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1272. return
  1273. }
  1274. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  1275. if err != nil {
  1276. s.renderClientMessagePage(w, r, util.I18nError500Title, getRespStatus(err),
  1277. util.NewI18nError(err, util.I18nErrorGetUser), "")
  1278. return
  1279. }
  1280. share := &dataprovider.Share{Scope: dataprovider.ShareScopeRead}
  1281. if user.Filters.DefaultSharesExpiration > 0 {
  1282. share.ExpiresAt = util.GetTimeAsMsSinceEpoch(time.Now().Add(24 * time.Hour * time.Duration(user.Filters.DefaultSharesExpiration)))
  1283. } else if user.Filters.MaxSharesExpiration > 0 {
  1284. share.ExpiresAt = util.GetTimeAsMsSinceEpoch(time.Now().Add(24 * time.Hour * time.Duration(user.Filters.MaxSharesExpiration)))
  1285. }
  1286. dirName := "/"
  1287. if _, ok := r.URL.Query()["path"]; ok {
  1288. dirName = util.CleanPath(r.URL.Query().Get("path"))
  1289. }
  1290. if _, ok := r.URL.Query()["files"]; ok {
  1291. files := r.URL.Query().Get("files")
  1292. var filesList []string
  1293. err := json.Unmarshal(util.StringToBytes(files), &filesList)
  1294. if err != nil {
  1295. s.renderClientBadRequestPage(w, r, err)
  1296. return
  1297. }
  1298. for _, f := range filesList {
  1299. if f != "" {
  1300. share.Paths = append(share.Paths, path.Join(dirName, f))
  1301. }
  1302. }
  1303. }
  1304. s.renderAddUpdateSharePage(w, r, share, nil, true)
  1305. }
  1306. func (s *httpdServer) handleClientUpdateShareGet(w http.ResponseWriter, r *http.Request) {
  1307. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1308. claims, err := getTokenClaims(r)
  1309. if err != nil || claims.Username == "" {
  1310. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1311. return
  1312. }
  1313. shareID := getURLParam(r, "id")
  1314. share, err := dataprovider.ShareExists(shareID, claims.Username)
  1315. if err == nil {
  1316. share.HideConfidentialData()
  1317. s.renderAddUpdateSharePage(w, r, &share, nil, false)
  1318. } else if errors.Is(err, util.ErrNotFound) {
  1319. s.renderClientNotFoundPage(w, r, err)
  1320. } else {
  1321. s.renderClientInternalServerErrorPage(w, r, err)
  1322. }
  1323. }
  1324. func (s *httpdServer) handleClientAddSharePost(w http.ResponseWriter, r *http.Request) {
  1325. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1326. claims, err := getTokenClaims(r)
  1327. if err != nil || claims.Username == "" {
  1328. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1329. return
  1330. }
  1331. share, err := getShareFromPostFields(r)
  1332. if err != nil {
  1333. s.renderAddUpdateSharePage(w, r, share, util.NewI18nError(err, util.I18nError500Message), true)
  1334. return
  1335. }
  1336. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1337. if err := verifyCSRFToken(r, s.csrfTokenAuth); err != nil {
  1338. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  1339. return
  1340. }
  1341. share.ID = 0
  1342. share.ShareID = util.GenerateUniqueID()
  1343. share.LastUseAt = 0
  1344. share.Username = claims.Username
  1345. if share.Password == "" {
  1346. if slices.Contains(claims.Permissions, sdk.WebClientShareNoPasswordDisabled) {
  1347. s.renderAddUpdateSharePage(w, r, share,
  1348. util.NewI18nError(util.NewValidationError("You are not allowed to share files/folders without password"), util.I18nErrorShareNoPwd),
  1349. true)
  1350. return
  1351. }
  1352. }
  1353. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  1354. if err != nil {
  1355. s.renderAddUpdateSharePage(w, r, share, util.NewI18nError(err, util.I18nErrorGetUser), true)
  1356. return
  1357. }
  1358. if err := user.CheckMaxShareExpiration(util.GetTimeFromMsecSinceEpoch(share.ExpiresAt)); err != nil {
  1359. s.renderAddUpdateSharePage(w, r, share, util.NewI18nError(
  1360. err,
  1361. util.I18nErrorShareExpirationOutOfRange,
  1362. util.I18nErrorArgs(
  1363. map[string]any{
  1364. "val": time.Now().Add(24 * time.Hour * time.Duration(user.Filters.MaxSharesExpiration+1)).UnixMilli(),
  1365. "formatParams": map[string]string{
  1366. "year": "numeric",
  1367. "month": "numeric",
  1368. "day": "numeric",
  1369. },
  1370. },
  1371. ),
  1372. ), true)
  1373. return
  1374. }
  1375. err = dataprovider.AddShare(share, claims.Username, ipAddr, claims.Role)
  1376. if err == nil {
  1377. http.Redirect(w, r, webClientSharesPath, http.StatusSeeOther)
  1378. } else {
  1379. s.renderAddUpdateSharePage(w, r, share, util.NewI18nError(err, util.I18nErrorShareGeneric), true)
  1380. }
  1381. }
  1382. func (s *httpdServer) handleClientUpdateSharePost(w http.ResponseWriter, r *http.Request) {
  1383. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1384. claims, err := getTokenClaims(r)
  1385. if err != nil || claims.Username == "" {
  1386. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1387. return
  1388. }
  1389. shareID := getURLParam(r, "id")
  1390. share, err := dataprovider.ShareExists(shareID, claims.Username)
  1391. if errors.Is(err, util.ErrNotFound) {
  1392. s.renderClientNotFoundPage(w, r, err)
  1393. return
  1394. } else if err != nil {
  1395. s.renderClientInternalServerErrorPage(w, r, err)
  1396. return
  1397. }
  1398. updatedShare, err := getShareFromPostFields(r)
  1399. if err != nil {
  1400. s.renderAddUpdateSharePage(w, r, updatedShare, util.NewI18nError(err, util.I18nError500Message), false)
  1401. return
  1402. }
  1403. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1404. if err := verifyCSRFToken(r, s.csrfTokenAuth); err != nil {
  1405. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  1406. return
  1407. }
  1408. updatedShare.ShareID = shareID
  1409. updatedShare.Username = claims.Username
  1410. if updatedShare.Password == redactedSecret {
  1411. updatedShare.Password = share.Password
  1412. }
  1413. if updatedShare.Password == "" {
  1414. if slices.Contains(claims.Permissions, sdk.WebClientShareNoPasswordDisabled) {
  1415. s.renderAddUpdateSharePage(w, r, updatedShare,
  1416. util.NewI18nError(util.NewValidationError("You are not allowed to share files/folders without password"), util.I18nErrorShareNoPwd),
  1417. false)
  1418. return
  1419. }
  1420. }
  1421. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  1422. if err != nil {
  1423. s.renderAddUpdateSharePage(w, r, updatedShare, util.NewI18nError(err, util.I18nErrorGetUser), false)
  1424. return
  1425. }
  1426. if err := user.CheckMaxShareExpiration(util.GetTimeFromMsecSinceEpoch(updatedShare.ExpiresAt)); err != nil {
  1427. s.renderAddUpdateSharePage(w, r, updatedShare, util.NewI18nError(
  1428. err,
  1429. util.I18nErrorShareExpirationOutOfRange,
  1430. util.I18nErrorArgs(
  1431. map[string]any{
  1432. "val": time.Now().Add(24 * time.Hour * time.Duration(user.Filters.MaxSharesExpiration+1)).UnixMilli(),
  1433. "formatParams": map[string]string{
  1434. "year": "numeric",
  1435. "month": "numeric",
  1436. "day": "numeric",
  1437. },
  1438. },
  1439. ),
  1440. ), false)
  1441. return
  1442. }
  1443. err = dataprovider.UpdateShare(updatedShare, claims.Username, ipAddr, claims.Role)
  1444. if err == nil {
  1445. http.Redirect(w, r, webClientSharesPath, http.StatusSeeOther)
  1446. } else {
  1447. s.renderAddUpdateSharePage(w, r, updatedShare, util.NewI18nError(err, util.I18nErrorShareGeneric), false)
  1448. }
  1449. }
  1450. func getAllShares(w http.ResponseWriter, r *http.Request) {
  1451. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1452. claims, err := getTokenClaims(r)
  1453. if err != nil || claims.Username == "" {
  1454. sendAPIResponse(w, r, nil, util.I18nErrorInvalidToken, http.StatusForbidden)
  1455. return
  1456. }
  1457. dataGetter := func(limit, offset int) ([]byte, int, error) {
  1458. shares, err := dataprovider.GetShares(limit, offset, dataprovider.OrderASC, claims.Username)
  1459. if err != nil {
  1460. return nil, 0, err
  1461. }
  1462. data, err := json.Marshal(shares)
  1463. return data, len(shares), err
  1464. }
  1465. streamJSONArray(w, defaultQueryLimit, dataGetter)
  1466. }
  1467. func (s *httpdServer) handleClientGetShares(w http.ResponseWriter, r *http.Request) {
  1468. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1469. data := clientSharesPage{
  1470. baseClientPage: s.getBaseClientPageData(util.I18nSharesTitle, webClientSharesPath, w, r),
  1471. BasePublicSharesURL: webClientPubSharesPath,
  1472. }
  1473. renderClientTemplate(w, templateClientShares, data)
  1474. }
  1475. func (s *httpdServer) handleClientGetProfile(w http.ResponseWriter, r *http.Request) {
  1476. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1477. s.renderClientProfilePage(w, r, nil)
  1478. }
  1479. func (s *httpdServer) handleWebClientChangePwd(w http.ResponseWriter, r *http.Request) {
  1480. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1481. s.renderClientChangePasswordPage(w, r, nil)
  1482. }
  1483. func (s *httpdServer) handleWebClientProfilePost(w http.ResponseWriter, r *http.Request) { //nolint:gocyclo
  1484. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1485. err := r.ParseForm()
  1486. if err != nil {
  1487. s.renderClientProfilePage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  1488. return
  1489. }
  1490. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1491. if err := verifyCSRFToken(r, s.csrfTokenAuth); err != nil {
  1492. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  1493. return
  1494. }
  1495. claims, err := getTokenClaims(r)
  1496. if err != nil || claims.Username == "" {
  1497. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1498. return
  1499. }
  1500. user, userMerged, err := dataprovider.GetUserVariants(claims.Username, "")
  1501. if err != nil {
  1502. s.renderClientProfilePage(w, r, util.NewI18nError(err, util.I18nErrorGetUser))
  1503. return
  1504. }
  1505. if !userMerged.CanUpdateProfile() {
  1506. s.renderClientForbiddenPage(w, r, util.NewI18nError(
  1507. errors.New("you are not allowed to change anything"),
  1508. util.I18nErrorNoPermissions,
  1509. ))
  1510. return
  1511. }
  1512. if userMerged.CanManagePublicKeys() {
  1513. for k := range r.Form {
  1514. if hasPrefixAndSuffix(k, "public_keys[", "][public_key]") {
  1515. r.Form.Add("public_keys", r.Form.Get(k))
  1516. }
  1517. }
  1518. user.PublicKeys = r.Form["public_keys"]
  1519. }
  1520. if userMerged.CanManageTLSCerts() {
  1521. for k := range r.Form {
  1522. if hasPrefixAndSuffix(k, "tls_certs[", "][tls_cert]") {
  1523. r.Form.Add("tls_certs", r.Form.Get(k))
  1524. }
  1525. }
  1526. user.Filters.TLSCerts = r.Form["tls_certs"]
  1527. }
  1528. if userMerged.CanChangeAPIKeyAuth() {
  1529. user.Filters.AllowAPIKeyAuth = r.Form.Get("allow_api_key_auth") != ""
  1530. }
  1531. if userMerged.CanChangeInfo() {
  1532. user.Email = strings.TrimSpace(r.Form.Get("email"))
  1533. user.Description = r.Form.Get("description")
  1534. }
  1535. err = dataprovider.UpdateUser(&user, dataprovider.ActionExecutorSelf, ipAddr, user.Role)
  1536. if err != nil {
  1537. s.renderClientProfilePage(w, r, util.NewI18nError(err, util.I18nError500Message))
  1538. return
  1539. }
  1540. s.renderClientMessagePage(w, r, util.I18nProfileTitle, http.StatusOK, nil, util.I18nProfileUpdated)
  1541. }
  1542. func (s *httpdServer) handleWebClientMFA(w http.ResponseWriter, r *http.Request) {
  1543. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1544. s.renderClientMFAPage(w, r)
  1545. }
  1546. func (s *httpdServer) handleWebClientTwoFactor(w http.ResponseWriter, r *http.Request) {
  1547. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1548. s.renderClientTwoFactorPage(w, r, nil)
  1549. }
  1550. func (s *httpdServer) handleWebClientTwoFactorRecovery(w http.ResponseWriter, r *http.Request) {
  1551. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1552. s.renderClientTwoFactorRecoveryPage(w, r, nil)
  1553. }
  1554. func getShareFromPostFields(r *http.Request) (*dataprovider.Share, error) {
  1555. share := &dataprovider.Share{}
  1556. if err := r.ParseForm(); err != nil {
  1557. return share, util.NewI18nError(err, util.I18nErrorInvalidForm)
  1558. }
  1559. for k := range r.Form {
  1560. if hasPrefixAndSuffix(k, "paths[", "][path]") {
  1561. r.Form.Add("paths", r.Form.Get(k))
  1562. }
  1563. }
  1564. share.Name = strings.TrimSpace(r.Form.Get("name"))
  1565. share.Description = r.Form.Get("description")
  1566. for _, p := range r.Form["paths"] {
  1567. if strings.TrimSpace(p) != "" {
  1568. share.Paths = append(share.Paths, p)
  1569. }
  1570. }
  1571. share.Password = strings.TrimSpace(r.Form.Get("password"))
  1572. share.AllowFrom = getSliceFromDelimitedValues(r.Form.Get("allowed_ip"), ",")
  1573. scope, err := strconv.Atoi(r.Form.Get("scope"))
  1574. if err != nil {
  1575. return share, util.NewI18nError(err, util.I18nErrorShareScope)
  1576. }
  1577. share.Scope = dataprovider.ShareScope(scope)
  1578. maxTokens, err := strconv.Atoi(r.Form.Get("max_tokens"))
  1579. if err != nil {
  1580. return share, util.NewI18nError(err, util.I18nErrorShareMaxTokens)
  1581. }
  1582. share.MaxTokens = maxTokens
  1583. expirationDateMillis := int64(0)
  1584. expirationDateString := strings.TrimSpace(r.Form.Get("expiration_date"))
  1585. if expirationDateString != "" {
  1586. expirationDate, err := time.Parse(webDateTimeFormat, expirationDateString)
  1587. if err != nil {
  1588. return share, util.NewI18nError(err, util.I18nErrorShareExpiration)
  1589. }
  1590. expirationDateMillis = util.GetTimeAsMsSinceEpoch(expirationDate)
  1591. }
  1592. share.ExpiresAt = expirationDateMillis
  1593. return share, nil
  1594. }
  1595. func (s *httpdServer) handleWebClientForgotPwd(w http.ResponseWriter, r *http.Request) {
  1596. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1597. if !smtp.IsEnabled() {
  1598. s.renderClientNotFoundPage(w, r, errors.New("this page does not exist"))
  1599. return
  1600. }
  1601. s.renderClientForgotPwdPage(w, r, nil)
  1602. }
  1603. func (s *httpdServer) handleWebClientForgotPwdPost(w http.ResponseWriter, r *http.Request) {
  1604. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1605. err := r.ParseForm()
  1606. if err != nil {
  1607. s.renderClientForgotPwdPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  1608. return
  1609. }
  1610. if err := verifyLoginCookieAndCSRFToken(r, s.csrfTokenAuth); err != nil {
  1611. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  1612. return
  1613. }
  1614. username := strings.TrimSpace(r.Form.Get("username"))
  1615. err = handleForgotPassword(r, username, false)
  1616. if err != nil {
  1617. s.renderClientForgotPwdPage(w, r, util.NewI18nError(err, util.I18nErrorPwdResetGeneric))
  1618. return
  1619. }
  1620. http.Redirect(w, r, webClientResetPwdPath, http.StatusFound)
  1621. }
  1622. func (s *httpdServer) handleWebClientPasswordReset(w http.ResponseWriter, r *http.Request) {
  1623. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1624. if !smtp.IsEnabled() {
  1625. s.renderClientNotFoundPage(w, r, errors.New("this page does not exist"))
  1626. return
  1627. }
  1628. s.renderClientResetPwdPage(w, r, nil)
  1629. }
  1630. func (s *httpdServer) handleClientViewPDF(w http.ResponseWriter, r *http.Request) {
  1631. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1632. name := r.URL.Query().Get("path")
  1633. if name == "" {
  1634. s.renderClientBadRequestPage(w, r, errors.New("no file specified"))
  1635. return
  1636. }
  1637. name = util.CleanPath(name)
  1638. data := viewPDFPage{
  1639. commonBasePage: getCommonBasePage(r),
  1640. Title: path.Base(name),
  1641. URL: fmt.Sprintf("%s?path=%s&_=%d", webClientGetPDFPath, url.QueryEscape(name), time.Now().UTC().Unix()),
  1642. Branding: s.binding.webClientBranding(),
  1643. }
  1644. renderClientTemplate(w, templateClientViewPDF, data)
  1645. }
  1646. func (s *httpdServer) handleClientGetPDF(w http.ResponseWriter, r *http.Request) {
  1647. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1648. claims, err := getTokenClaims(r)
  1649. if err != nil || claims.Username == "" {
  1650. s.renderClientForbiddenPage(w, r, util.NewI18nError(errInvalidTokenClaims, util.I18nErrorInvalidToken))
  1651. return
  1652. }
  1653. name := r.URL.Query().Get("path")
  1654. if name == "" {
  1655. s.renderClientBadRequestPage(w, r, util.NewI18nError(errors.New("no file specified"), util.I18nError400Message))
  1656. return
  1657. }
  1658. name = util.CleanPath(name)
  1659. user, err := dataprovider.GetUserWithGroupSettings(claims.Username, "")
  1660. if err != nil {
  1661. s.renderClientMessagePage(w, r, util.I18nError500Title, getRespStatus(err),
  1662. util.NewI18nError(err, util.I18nErrorGetUser), "")
  1663. return
  1664. }
  1665. connID := xid.New().String()
  1666. protocol := getProtocolFromRequest(r)
  1667. connectionID := fmt.Sprintf("%v_%v", protocol, connID)
  1668. if err := checkHTTPClientUser(&user, r, connectionID, false); err != nil {
  1669. s.renderClientForbiddenPage(w, r, err)
  1670. return
  1671. }
  1672. connection := &Connection{
  1673. BaseConnection: common.NewBaseConnection(connID, protocol, util.GetHTTPLocalAddress(r),
  1674. r.RemoteAddr, user),
  1675. request: r,
  1676. }
  1677. if err = common.Connections.Add(connection); err != nil {
  1678. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1679. util.NewI18nError(err, util.I18nError429Message), "")
  1680. return
  1681. }
  1682. defer common.Connections.Remove(connection.GetID())
  1683. info, err := connection.Stat(name, 0)
  1684. if err != nil {
  1685. status := getRespStatus(err)
  1686. s.renderClientMessagePage(w, r, util.I18nErrorPDFTitle, status, util.NewI18nError(err, i18nFsMsg(status)), "")
  1687. return
  1688. }
  1689. if info.IsDir() {
  1690. s.renderClientBadRequestPage(w, r, util.NewI18nError(fmt.Errorf("%q is not a file", name), util.I18nErrorPDFMessage))
  1691. return
  1692. }
  1693. connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
  1694. if err := s.ensurePDF(w, r, name, connection); err != nil {
  1695. return
  1696. }
  1697. downloadFile(w, r, connection, name, info, true, nil) //nolint:errcheck
  1698. }
  1699. func (s *httpdServer) ensurePDF(w http.ResponseWriter, r *http.Request, name string, connection *Connection) error {
  1700. reader, err := connection.getFileReader(name, 0, r.Method)
  1701. if err != nil {
  1702. s.renderClientMessagePage(w, r, util.I18nErrorPDFTitle,
  1703. getRespStatus(err), util.NewI18nError(err, util.I18nError500Message), "")
  1704. return err
  1705. }
  1706. defer reader.Close()
  1707. var b bytes.Buffer
  1708. _, err = io.CopyN(&b, reader, 128)
  1709. if err != nil {
  1710. s.renderClientMessagePage(w, r, util.I18nErrorPDFTitle, getRespStatus(err),
  1711. util.NewI18nError(err, util.I18nErrorPDFMessage), "")
  1712. return err
  1713. }
  1714. if ctype := http.DetectContentType(b.Bytes()); ctype != "application/pdf" {
  1715. connection.Log(logger.LevelDebug, "detected %q content type, expected PDF, file %q", ctype, name)
  1716. err := fmt.Errorf("the file %q does not look like a PDF", name)
  1717. s.renderClientBadRequestPage(w, r, util.NewI18nError(err, util.I18nErrorPDFMessage))
  1718. return err
  1719. }
  1720. return nil
  1721. }
  1722. func (s *httpdServer) handleClientShareLoginGet(w http.ResponseWriter, r *http.Request) {
  1723. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1724. s.renderShareLoginPage(w, r, nil)
  1725. }
  1726. func (s *httpdServer) handleClientShareLoginPost(w http.ResponseWriter, r *http.Request) {
  1727. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1728. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1729. if err := r.ParseForm(); err != nil {
  1730. s.renderShareLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  1731. return
  1732. }
  1733. if err := verifyLoginCookieAndCSRFToken(r, s.csrfTokenAuth); err != nil {
  1734. s.renderShareLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  1735. return
  1736. }
  1737. invalidateToken(r, true)
  1738. shareID := getURLParam(r, "id")
  1739. share, err := dataprovider.ShareExists(shareID, "")
  1740. if err != nil {
  1741. s.renderShareLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCredentials))
  1742. return
  1743. }
  1744. match, err := share.CheckCredentials(strings.TrimSpace(r.Form.Get("share_password")))
  1745. if !match || err != nil {
  1746. s.renderShareLoginPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials))
  1747. return
  1748. }
  1749. next := path.Clean(r.URL.Query().Get("next"))
  1750. baseShareURL := path.Join(webClientPubSharesPath, share.ShareID)
  1751. isRedirect, redirectTo := checkShareRedirectURL(next, baseShareURL)
  1752. c := jwtTokenClaims{
  1753. Username: shareID,
  1754. }
  1755. if isRedirect {
  1756. c.Ref = next
  1757. }
  1758. err = c.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebShare, ipAddr)
  1759. if err != nil {
  1760. s.renderShareLoginPage(w, r, util.NewI18nError(err, util.I18nError500Message))
  1761. return
  1762. }
  1763. if isRedirect {
  1764. http.Redirect(w, r, redirectTo, http.StatusFound)
  1765. return
  1766. }
  1767. s.renderClientMessagePage(w, r, util.I18nSharedFilesTitle, http.StatusOK, nil, util.I18nShareLoginOK)
  1768. }
  1769. func (s *httpdServer) handleClientShareLogout(w http.ResponseWriter, r *http.Request) {
  1770. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1771. shareID := getURLParam(r, "id")
  1772. claims, err := s.getShareClaims(r, shareID)
  1773. if err != nil {
  1774. s.renderClientMessagePage(w, r, util.I18nShareAccessErrorTitle, http.StatusForbidden,
  1775. util.NewI18nError(err, util.I18nErrorInvalidToken), "")
  1776. return
  1777. }
  1778. removeCookie(w, r, webBaseClientPath)
  1779. redirectURL := path.Join(webClientPubSharesPath, shareID, fmt.Sprintf("login?next=%s", url.QueryEscape(claims.Ref)))
  1780. http.Redirect(w, r, redirectURL, http.StatusFound)
  1781. }
  1782. func (s *httpdServer) handleClientSharedFile(w http.ResponseWriter, r *http.Request) {
  1783. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1784. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeRead}
  1785. share, _, err := s.checkPublicShare(w, r, validScopes)
  1786. if err != nil {
  1787. return
  1788. }
  1789. query := ""
  1790. if r.URL.RawQuery != "" {
  1791. query = "?" + r.URL.RawQuery
  1792. }
  1793. s.renderShareDownloadPage(w, r, &share, path.Join(webClientPubSharesPath, share.ShareID)+query)
  1794. }
  1795. func (s *httpdServer) handleClientCheckExist(w http.ResponseWriter, r *http.Request) {
  1796. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1797. connection, err := getUserConnection(w, r)
  1798. if err != nil {
  1799. return
  1800. }
  1801. defer common.Connections.Remove(connection.GetID())
  1802. name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
  1803. doCheckExist(w, r, connection, name)
  1804. }
  1805. func (s *httpdServer) handleClientShareCheckExist(w http.ResponseWriter, r *http.Request) {
  1806. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1807. validScopes := []dataprovider.ShareScope{dataprovider.ShareScopeReadWrite}
  1808. share, connection, err := s.checkPublicShare(w, r, validScopes)
  1809. if err != nil {
  1810. return
  1811. }
  1812. if err := validateBrowsableShare(share, connection); err != nil {
  1813. sendAPIResponse(w, r, err, "", getRespStatus(err))
  1814. return
  1815. }
  1816. name, err := getBrowsableSharedPath(share.Paths[0], r)
  1817. if err != nil {
  1818. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  1819. return
  1820. }
  1821. if err = common.Connections.Add(connection); err != nil {
  1822. sendAPIResponse(w, r, err, "Unable to add connection", http.StatusTooManyRequests)
  1823. return
  1824. }
  1825. defer common.Connections.Remove(connection.GetID())
  1826. doCheckExist(w, r, connection, name)
  1827. }
  1828. type filesToCheck struct {
  1829. Files []string `json:"files"`
  1830. }
  1831. func doCheckExist(w http.ResponseWriter, r *http.Request, connection *Connection, name string) {
  1832. var filesList filesToCheck
  1833. err := render.DecodeJSON(r.Body, &filesList)
  1834. if err != nil {
  1835. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  1836. return
  1837. }
  1838. if len(filesList.Files) == 0 {
  1839. sendAPIResponse(w, r, errors.New("files to be checked are mandatory"), "", http.StatusBadRequest)
  1840. return
  1841. }
  1842. lister, err := connection.ListDir(name)
  1843. if err != nil {
  1844. sendAPIResponse(w, r, err, "Unable to get directory contents", getMappedStatusCode(err))
  1845. return
  1846. }
  1847. defer lister.Close()
  1848. dataGetter := func(limit, _ int) ([]byte, int, error) {
  1849. contents, err := lister.Next(limit)
  1850. if errors.Is(err, io.EOF) {
  1851. err = nil
  1852. }
  1853. if err != nil {
  1854. return nil, 0, err
  1855. }
  1856. existing := make([]map[string]any, 0)
  1857. for _, info := range contents {
  1858. if slices.Contains(filesList.Files, info.Name()) {
  1859. res := make(map[string]any)
  1860. res["name"] = info.Name()
  1861. if info.IsDir() {
  1862. res["type"] = "1"
  1863. res["size"] = ""
  1864. } else {
  1865. res["type"] = "2"
  1866. res["size"] = info.Size()
  1867. }
  1868. existing = append(existing, res)
  1869. }
  1870. }
  1871. data, err := json.Marshal(existing)
  1872. count := limit
  1873. if len(existing) == 0 {
  1874. count = 0
  1875. }
  1876. return data, count, err
  1877. }
  1878. streamJSONArray(w, defaultQueryLimit, dataGetter)
  1879. }
  1880. func checkShareRedirectURL(next, base string) (bool, string) {
  1881. if !strings.HasPrefix(next, base) {
  1882. return false, ""
  1883. }
  1884. if next == base {
  1885. return true, path.Join(next, "download")
  1886. }
  1887. baseURL, err := url.Parse(base)
  1888. if err != nil {
  1889. return false, ""
  1890. }
  1891. nextURL, err := url.Parse(next)
  1892. if err != nil {
  1893. return false, ""
  1894. }
  1895. if nextURL.Path == baseURL.Path {
  1896. redirectURL := nextURL.JoinPath("download")
  1897. return true, redirectURL.String()
  1898. }
  1899. return true, next
  1900. }
  1901. func getWebTask(w http.ResponseWriter, r *http.Request) {
  1902. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1903. claims, err := getTokenClaims(r)
  1904. if err != nil || claims.Username == "" {
  1905. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  1906. return
  1907. }
  1908. taskID := getURLParam(r, "id")
  1909. task, err := webTaskMgr.Get(taskID)
  1910. if err != nil {
  1911. sendAPIResponse(w, r, err, "Unable to get task", getMappedStatusCode(err))
  1912. return
  1913. }
  1914. if task.User != claims.Username {
  1915. sendAPIResponse(w, r, nil, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  1916. return
  1917. }
  1918. render.JSON(w, r, task)
  1919. }
  1920. func taskDeleteDir(w http.ResponseWriter, r *http.Request) {
  1921. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1922. connection, err := getUserConnection(w, r)
  1923. if err != nil {
  1924. return
  1925. }
  1926. name := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
  1927. task := webTaskData{
  1928. ID: connection.GetID(),
  1929. User: connection.GetUsername(),
  1930. Path: name,
  1931. Timestamp: util.GetTimeAsMsSinceEpoch(time.Now()),
  1932. Status: 0,
  1933. }
  1934. if err := webTaskMgr.Add(task); err != nil {
  1935. common.Connections.Remove(connection.GetID())
  1936. sendAPIResponse(w, r, nil, "Unable to create task", http.StatusInternalServerError)
  1937. return
  1938. }
  1939. go executeDeleteTask(connection, task)
  1940. sendAPIResponse(w, r, nil, task.ID, http.StatusAccepted)
  1941. }
  1942. func taskRenameFsEntry(w http.ResponseWriter, r *http.Request) {
  1943. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1944. connection, err := getUserConnection(w, r)
  1945. if err != nil {
  1946. return
  1947. }
  1948. oldName := connection.User.GetCleanedPath(r.URL.Query().Get("path"))
  1949. newName := connection.User.GetCleanedPath(r.URL.Query().Get("target"))
  1950. task := webTaskData{
  1951. ID: connection.GetID(),
  1952. User: connection.GetUsername(),
  1953. Path: oldName,
  1954. Target: newName,
  1955. Timestamp: util.GetTimeAsMsSinceEpoch(time.Now()),
  1956. Status: 0,
  1957. }
  1958. if err := webTaskMgr.Add(task); err != nil {
  1959. common.Connections.Remove(connection.GetID())
  1960. sendAPIResponse(w, r, nil, "Unable to create task", http.StatusInternalServerError)
  1961. return
  1962. }
  1963. go executeRenameTask(connection, task)
  1964. sendAPIResponse(w, r, nil, task.ID, http.StatusAccepted)
  1965. }
  1966. func taskCopyFsEntry(w http.ResponseWriter, r *http.Request) {
  1967. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1968. connection, err := getUserConnection(w, r)
  1969. if err != nil {
  1970. return
  1971. }
  1972. source := r.URL.Query().Get("path")
  1973. target := r.URL.Query().Get("target")
  1974. copyFromSource := strings.HasSuffix(source, "/")
  1975. copyInTarget := strings.HasSuffix(target, "/")
  1976. source = connection.User.GetCleanedPath(source)
  1977. target = connection.User.GetCleanedPath(target)
  1978. if copyFromSource {
  1979. source += "/"
  1980. }
  1981. if copyInTarget {
  1982. target += "/"
  1983. }
  1984. task := webTaskData{
  1985. ID: connection.GetID(),
  1986. User: connection.GetUsername(),
  1987. Path: source,
  1988. Target: target,
  1989. Timestamp: util.GetTimeAsMsSinceEpoch(time.Now()),
  1990. Status: 0,
  1991. }
  1992. if err := webTaskMgr.Add(task); err != nil {
  1993. common.Connections.Remove(connection.GetID())
  1994. sendAPIResponse(w, r, nil, "Unable to create task", http.StatusInternalServerError)
  1995. return
  1996. }
  1997. go executeCopyTask(connection, task)
  1998. sendAPIResponse(w, r, nil, task.ID, http.StatusAccepted)
  1999. }
  2000. func executeDeleteTask(conn *Connection, task webTaskData) {
  2001. done := make(chan bool)
  2002. defer func() {
  2003. close(done)
  2004. common.Connections.Remove(conn.GetID())
  2005. }()
  2006. go keepAliveTask(task, done, 2*time.Minute)
  2007. status := http.StatusOK
  2008. if err := conn.RemoveAll(task.Path); err != nil {
  2009. status = getMappedStatusCode(err)
  2010. }
  2011. task.Timestamp = util.GetTimeAsMsSinceEpoch(time.Now())
  2012. task.Status = status
  2013. err := webTaskMgr.Add(task)
  2014. conn.Log(logger.LevelDebug, "delete task finished, status: %d, update task err: %v", status, err)
  2015. }
  2016. func executeRenameTask(conn *Connection, task webTaskData) {
  2017. done := make(chan bool)
  2018. defer func() {
  2019. close(done)
  2020. common.Connections.Remove(conn.GetID())
  2021. }()
  2022. go keepAliveTask(task, done, 2*time.Minute)
  2023. status := http.StatusOK
  2024. if !conn.IsSameResource(task.Path, task.Target) {
  2025. if err := conn.Copy(task.Path, task.Target); err != nil {
  2026. status = getMappedStatusCode(err)
  2027. task.Timestamp = util.GetTimeAsMsSinceEpoch(time.Now())
  2028. task.Status = status
  2029. err = webTaskMgr.Add(task)
  2030. conn.Log(logger.LevelDebug, "copy step for rename task finished, status: %d, update task err: %v", status, err)
  2031. return
  2032. }
  2033. if err := conn.RemoveAll(task.Path); err != nil {
  2034. status = getMappedStatusCode(err)
  2035. }
  2036. } else {
  2037. if err := conn.Rename(task.Path, task.Target); err != nil {
  2038. status = getMappedStatusCode(err)
  2039. }
  2040. }
  2041. task.Timestamp = util.GetTimeAsMsSinceEpoch(time.Now())
  2042. task.Status = status
  2043. err := webTaskMgr.Add(task)
  2044. conn.Log(logger.LevelDebug, "rename task finished, status: %d, update task err: %v", status, err)
  2045. }
  2046. func executeCopyTask(conn *Connection, task webTaskData) {
  2047. done := make(chan bool)
  2048. defer func() {
  2049. close(done)
  2050. common.Connections.Remove(conn.GetID())
  2051. }()
  2052. go keepAliveTask(task, done, 2*time.Minute)
  2053. status := http.StatusOK
  2054. if err := conn.Copy(task.Path, task.Target); err != nil {
  2055. status = getMappedStatusCode(err)
  2056. }
  2057. task.Timestamp = util.GetTimeAsMsSinceEpoch(time.Now())
  2058. task.Status = status
  2059. err := webTaskMgr.Add(task)
  2060. conn.Log(logger.LevelDebug, "copy task finished, status: %d, update task err: %v", status, err)
  2061. }
  2062. func keepAliveTask(task webTaskData, done chan bool, interval time.Duration) {
  2063. ticker := time.NewTicker(interval)
  2064. defer func() {
  2065. ticker.Stop()
  2066. }()
  2067. for {
  2068. select {
  2069. case <-done:
  2070. return
  2071. case <-ticker.C:
  2072. task.Timestamp = util.GetTimeAsMsSinceEpoch(time.Now())
  2073. err := webTaskMgr.Add(task)
  2074. logger.Debug(logSender, task.ID, "task timestamp updated, err: %v", err)
  2075. }
  2076. }
  2077. }