webclient.go 73 KB

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