webclient.go 67 KB

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