webclient.go 75 KB

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