scp.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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 sftpd
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "math"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "runtime/debug"
  24. "strconv"
  25. "strings"
  26. "github.com/drakkan/sftpgo/v2/internal/common"
  27. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  28. "github.com/drakkan/sftpgo/v2/internal/logger"
  29. "github.com/drakkan/sftpgo/v2/internal/vfs"
  30. )
  31. var (
  32. okMsg = []byte{0x00}
  33. warnMsg = []byte{0x01} // must be followed by an optional message and a newline
  34. errMsg = []byte{0x02} // must be followed by an optional message and a newline
  35. newLine = []byte{0x0A}
  36. )
  37. type scpCommand struct {
  38. sshCommand
  39. }
  40. func (c *scpCommand) handle() (err error) {
  41. defer func() {
  42. if r := recover(); r != nil {
  43. logger.Error(logSender, "", "panic in handle scp command: %q stack trace: %v", r, string(debug.Stack()))
  44. err = common.ErrGenericFailure
  45. }
  46. }()
  47. if err := common.Connections.Add(c.connection); err != nil {
  48. logger.Info(logSender, "", "unable to add SCP connection: %v", err)
  49. return err
  50. }
  51. defer common.Connections.Remove(c.connection.GetID())
  52. destPath := c.getDestPath()
  53. c.connection.Log(logger.LevelDebug, "handle scp command, args: %v user: %s, dest path: %q",
  54. c.args, c.connection.User.Username, destPath)
  55. if c.hasFlag("t") {
  56. // -t means "to", so upload
  57. err = c.sendConfirmationMessage()
  58. if err != nil {
  59. return err
  60. }
  61. err = c.handleRecursiveUpload()
  62. if err != nil {
  63. return err
  64. }
  65. } else if c.hasFlag("f") {
  66. // -f means "from" so download
  67. err = c.readConfirmationMessage()
  68. if err != nil {
  69. return err
  70. }
  71. err = c.handleDownload(destPath)
  72. if err != nil {
  73. return err
  74. }
  75. } else {
  76. err = fmt.Errorf("scp command not supported, args: %v", c.args)
  77. c.connection.Log(logger.LevelDebug, "unsupported scp command, args: %v", c.args)
  78. }
  79. c.sendExitStatus(err)
  80. return err
  81. }
  82. func (c *scpCommand) handleRecursiveUpload() error {
  83. numDirs := 0
  84. destPath := c.getDestPath()
  85. for {
  86. fs, err := c.connection.User.GetFilesystemForPath(destPath, c.connection.ID)
  87. if err != nil {
  88. c.connection.Log(logger.LevelError, "error uploading file %q: %+v", destPath, err)
  89. c.sendErrorMessage(nil, fmt.Errorf("unable to get fs for path %q", destPath))
  90. return err
  91. }
  92. command, err := c.getNextUploadProtocolMessage()
  93. if err != nil {
  94. if errors.Is(err, io.EOF) {
  95. return nil
  96. }
  97. c.sendErrorMessage(fs, err)
  98. return err
  99. }
  100. if strings.HasPrefix(command, "E") {
  101. numDirs--
  102. c.connection.Log(logger.LevelDebug, "received end dir command, num dirs: %v", numDirs)
  103. if numDirs < 0 {
  104. err = errors.New("unacceptable end dir command")
  105. c.sendErrorMessage(nil, err)
  106. return err
  107. }
  108. // the destination dir is now the parent directory
  109. destPath = path.Join(destPath, "..")
  110. } else {
  111. sizeToRead, name, err := c.parseUploadMessage(fs, command)
  112. if err != nil {
  113. return err
  114. }
  115. if strings.HasPrefix(command, "D") {
  116. numDirs++
  117. destPath = path.Join(destPath, name)
  118. fs, err = c.connection.User.GetFilesystemForPath(destPath, c.connection.ID)
  119. if err != nil {
  120. c.connection.Log(logger.LevelError, "error uploading file %q: %+v", destPath, err)
  121. c.sendErrorMessage(nil, fmt.Errorf("unable to get fs for path %q", destPath))
  122. return err
  123. }
  124. err = c.handleCreateDir(fs, destPath)
  125. if err != nil {
  126. return err
  127. }
  128. c.connection.Log(logger.LevelDebug, "received start dir command, num dirs: %v destPath: %q", numDirs, destPath)
  129. } else if strings.HasPrefix(command, "C") {
  130. err = c.handleUpload(c.getFileUploadDestPath(fs, destPath, name), sizeToRead)
  131. if err != nil {
  132. return err
  133. }
  134. }
  135. }
  136. err = c.sendConfirmationMessage()
  137. if err != nil {
  138. return err
  139. }
  140. }
  141. }
  142. func (c *scpCommand) handleCreateDir(fs vfs.Fs, dirPath string) error {
  143. c.connection.UpdateLastActivity()
  144. p, err := fs.ResolvePath(dirPath)
  145. if err != nil {
  146. c.connection.Log(logger.LevelError, "error creating dir: %q, invalid file path, err: %v", dirPath, err)
  147. c.sendErrorMessage(fs, err)
  148. return err
  149. }
  150. if !c.connection.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(dirPath)) {
  151. c.connection.Log(logger.LevelError, "error creating dir: %q, permission denied", dirPath)
  152. c.sendErrorMessage(fs, common.ErrPermissionDenied)
  153. return common.ErrPermissionDenied
  154. }
  155. info, err := c.connection.DoStat(dirPath, 1, true)
  156. if err == nil && info.IsDir() {
  157. return nil
  158. }
  159. err = c.createDir(fs, p)
  160. if err != nil {
  161. return err
  162. }
  163. c.connection.Log(logger.LevelDebug, "created dir %q", dirPath)
  164. return nil
  165. }
  166. // we need to close the transfer if we have an error
  167. func (c *scpCommand) getUploadFileData(sizeToRead int64, transfer *transfer) error {
  168. err := c.sendConfirmationMessage()
  169. if err != nil {
  170. transfer.TransferError(err)
  171. transfer.Close()
  172. return err
  173. }
  174. if sizeToRead > 0 {
  175. // we could replace this method with io.CopyN implementing "Write" method in transfer struct
  176. remaining := sizeToRead
  177. buf := make([]byte, int64(math.Min(32768, float64(sizeToRead))))
  178. for {
  179. n, err := c.connection.channel.Read(buf)
  180. if err != nil {
  181. transfer.TransferError(err)
  182. transfer.Close()
  183. c.sendErrorMessage(transfer.Fs, err)
  184. return err
  185. }
  186. _, err = transfer.WriteAt(buf[:n], sizeToRead-remaining)
  187. if err != nil {
  188. transfer.Close()
  189. c.sendErrorMessage(transfer.Fs, err)
  190. return err
  191. }
  192. remaining -= int64(n)
  193. if remaining <= 0 {
  194. break
  195. }
  196. if remaining < int64(len(buf)) {
  197. buf = make([]byte, remaining)
  198. }
  199. }
  200. }
  201. err = c.readConfirmationMessage()
  202. if err != nil {
  203. transfer.TransferError(err)
  204. transfer.Close()
  205. return err
  206. }
  207. err = transfer.Close()
  208. if err != nil {
  209. c.sendErrorMessage(transfer.Fs, err)
  210. return err
  211. }
  212. return nil
  213. }
  214. func (c *scpCommand) handleUploadFile(fs vfs.Fs, resolvedPath, filePath string, sizeToRead int64, isNewFile bool, fileSize int64, requestPath string) error {
  215. diskQuota, transferQuota := c.connection.HasSpace(isNewFile, false, requestPath)
  216. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  217. err := fmt.Errorf("denying file write due to quota limits")
  218. c.connection.Log(logger.LevelError, "error uploading file: %q, err: %v", filePath, err)
  219. c.sendErrorMessage(nil, err)
  220. return err
  221. }
  222. _, err := common.ExecutePreAction(c.connection.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath,
  223. fileSize, os.O_TRUNC)
  224. if err != nil {
  225. c.connection.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  226. err = c.connection.GetPermissionDeniedError()
  227. c.sendErrorMessage(fs, err)
  228. return err
  229. }
  230. maxWriteSize, _ := c.connection.GetMaxWriteSize(diskQuota, false, fileSize, fs.IsUploadResumeSupported())
  231. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.connection.GetCreateChecks(requestPath, isNewFile, false))
  232. if err != nil {
  233. c.connection.Log(logger.LevelError, "error creating file %q: %v", resolvedPath, err)
  234. c.sendErrorMessage(fs, err)
  235. return err
  236. }
  237. initialSize := int64(0)
  238. truncatedSize := int64(0) // bytes truncated and not included in quota
  239. if !isNewFile {
  240. if vfs.HasTruncateSupport(fs) {
  241. vfolder, err := c.connection.User.GetVirtualFolderForPath(path.Dir(requestPath))
  242. if err == nil {
  243. dataprovider.UpdateUserFolderQuota(&vfolder, &c.connection.User, 0, -fileSize, false)
  244. } else {
  245. dataprovider.UpdateUserQuota(&c.connection.User, 0, -fileSize, false) //nolint:errcheck
  246. }
  247. } else {
  248. initialSize = fileSize
  249. truncatedSize = initialSize
  250. }
  251. if maxWriteSize > 0 {
  252. maxWriteSize += fileSize
  253. }
  254. }
  255. vfs.SetPathPermissions(fs, filePath, c.connection.User.GetUID(), c.connection.User.GetGID())
  256. baseTransfer := common.NewBaseTransfer(file, c.connection.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  257. common.TransferUpload, 0, initialSize, maxWriteSize, truncatedSize, isNewFile, fs, transferQuota)
  258. t := newTransfer(baseTransfer, w, nil, nil)
  259. return c.getUploadFileData(sizeToRead, t)
  260. }
  261. func (c *scpCommand) handleUpload(uploadFilePath string, sizeToRead int64) error {
  262. c.connection.UpdateLastActivity()
  263. fs, p, err := c.connection.GetFsAndResolvedPath(uploadFilePath)
  264. if err != nil {
  265. c.connection.Log(logger.LevelError, "error uploading file: %q, err: %v", uploadFilePath, err)
  266. c.sendErrorMessage(nil, err)
  267. return err
  268. }
  269. if ok, _ := c.connection.User.IsFileAllowed(uploadFilePath); !ok {
  270. c.connection.Log(logger.LevelWarn, "writing file %q is not allowed", uploadFilePath)
  271. c.sendErrorMessage(fs, c.connection.GetPermissionDeniedError())
  272. return common.ErrPermissionDenied
  273. }
  274. filePath := p
  275. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  276. filePath = fs.GetAtomicUploadPath(p)
  277. }
  278. stat, statErr := fs.Lstat(p)
  279. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  280. if !c.connection.User.HasPerm(dataprovider.PermUpload, path.Dir(uploadFilePath)) {
  281. c.connection.Log(logger.LevelWarn, "cannot upload file: %q, permission denied", uploadFilePath)
  282. c.sendErrorMessage(fs, common.ErrPermissionDenied)
  283. return common.ErrPermissionDenied
  284. }
  285. return c.handleUploadFile(fs, p, filePath, sizeToRead, true, 0, uploadFilePath)
  286. }
  287. if statErr != nil {
  288. c.connection.Log(logger.LevelError, "error performing file stat %q: %v", p, statErr)
  289. c.sendErrorMessage(fs, statErr)
  290. return statErr
  291. }
  292. if stat.IsDir() {
  293. c.connection.Log(logger.LevelError, "attempted to open a directory for writing to: %q", p)
  294. err = fmt.Errorf("attempted to open a directory for writing: %q", p)
  295. c.sendErrorMessage(fs, err)
  296. return err
  297. }
  298. if !c.connection.User.HasPerm(dataprovider.PermOverwrite, uploadFilePath) {
  299. c.connection.Log(logger.LevelWarn, "cannot overwrite file: %q, permission denied", uploadFilePath)
  300. c.sendErrorMessage(fs, common.ErrPermissionDenied)
  301. return common.ErrPermissionDenied
  302. }
  303. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  304. _, _, err = fs.Rename(p, filePath)
  305. if err != nil {
  306. c.connection.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %q, dest: %q, err: %v",
  307. p, filePath, err)
  308. c.sendErrorMessage(fs, err)
  309. return err
  310. }
  311. }
  312. return c.handleUploadFile(fs, p, filePath, sizeToRead, false, stat.Size(), uploadFilePath)
  313. }
  314. func (c *scpCommand) sendDownloadProtocolMessages(virtualDirPath string, stat os.FileInfo) error {
  315. var err error
  316. if c.sendFileTime() {
  317. modTime := stat.ModTime().UnixNano() / 1000000000
  318. tCommand := fmt.Sprintf("T%d 0 %d 0\n", modTime, modTime)
  319. err = c.sendProtocolMessage(tCommand)
  320. if err != nil {
  321. return err
  322. }
  323. err = c.readConfirmationMessage()
  324. if err != nil {
  325. return err
  326. }
  327. }
  328. dirName := path.Base(virtualDirPath)
  329. if dirName == "/" || dirName == "." {
  330. dirName = c.connection.User.Username
  331. }
  332. fileMode := fmt.Sprintf("D%v 0 %v\n", getFileModeAsString(stat.Mode(), stat.IsDir()), dirName)
  333. err = c.sendProtocolMessage(fileMode)
  334. if err != nil {
  335. return err
  336. }
  337. err = c.readConfirmationMessage()
  338. return err
  339. }
  340. // We send first all the files in the root directory and then the directories.
  341. // For each directory we recursively call this method again
  342. func (c *scpCommand) handleRecursiveDownload(fs vfs.Fs, dirPath, virtualPath string, stat os.FileInfo) error {
  343. var err error
  344. if c.isRecursive() {
  345. c.connection.Log(logger.LevelDebug, "recursive download, dir path %q virtual path %q", dirPath, virtualPath)
  346. err = c.sendDownloadProtocolMessages(virtualPath, stat)
  347. if err != nil {
  348. return err
  349. }
  350. // dirPath is a fs path, not a virtual path
  351. lister, err := fs.ReadDir(dirPath)
  352. if err != nil {
  353. c.sendErrorMessage(fs, err)
  354. return err
  355. }
  356. defer lister.Close()
  357. vdirs := c.connection.User.GetVirtualFoldersInfo(virtualPath)
  358. var dirs []string
  359. for {
  360. files, err := lister.Next(vfs.ListerBatchSize)
  361. finished := errors.Is(err, io.EOF)
  362. if err != nil && !finished {
  363. c.sendErrorMessage(fs, err)
  364. return err
  365. }
  366. files = c.connection.User.FilterListDir(files, fs.GetRelativePath(dirPath))
  367. if len(vdirs) > 0 {
  368. files = append(files, vdirs...)
  369. vdirs = nil
  370. }
  371. for _, file := range files {
  372. filePath := fs.GetRelativePath(fs.Join(dirPath, file.Name()))
  373. if file.Mode().IsRegular() || file.Mode()&os.ModeSymlink != 0 {
  374. err = c.handleDownload(filePath)
  375. if err != nil {
  376. c.sendErrorMessage(fs, err)
  377. return err
  378. }
  379. } else if file.IsDir() {
  380. dirs = append(dirs, filePath)
  381. }
  382. }
  383. if finished {
  384. break
  385. }
  386. }
  387. lister.Close()
  388. return c.downloadDirs(fs, dirs)
  389. }
  390. err = errors.New("unable to send directory for non recursive copy")
  391. c.sendErrorMessage(nil, err)
  392. return err
  393. }
  394. func (c *scpCommand) downloadDirs(fs vfs.Fs, dirs []string) error {
  395. for _, dir := range dirs {
  396. if err := c.handleDownload(dir); err != nil {
  397. c.sendErrorMessage(fs, err)
  398. return err
  399. }
  400. }
  401. if err := c.sendProtocolMessage("E\n"); err != nil {
  402. return err
  403. }
  404. return c.readConfirmationMessage()
  405. }
  406. func (c *scpCommand) sendDownloadFileData(fs vfs.Fs, filePath string, stat os.FileInfo, transfer *transfer) error {
  407. var err error
  408. if c.sendFileTime() {
  409. modTime := stat.ModTime().UnixNano() / 1000000000
  410. tCommand := fmt.Sprintf("T%d 0 %d 0\n", modTime, modTime)
  411. err = c.sendProtocolMessage(tCommand)
  412. if err != nil {
  413. return err
  414. }
  415. err = c.readConfirmationMessage()
  416. if err != nil {
  417. return err
  418. }
  419. }
  420. if vfs.IsCryptOsFs(fs) {
  421. stat = fs.(*vfs.CryptFs).ConvertFileInfo(stat)
  422. }
  423. fileSize := stat.Size()
  424. readed := int64(0)
  425. fileMode := fmt.Sprintf("C%v %v %v\n", getFileModeAsString(stat.Mode(), stat.IsDir()), fileSize, filepath.Base(filePath))
  426. err = c.sendProtocolMessage(fileMode)
  427. if err != nil {
  428. return err
  429. }
  430. err = c.readConfirmationMessage()
  431. if err != nil {
  432. return err
  433. }
  434. // we could replace this method with io.CopyN implementing "Read" method in transfer struct
  435. buf := make([]byte, 32768)
  436. var n int
  437. for {
  438. n, err = transfer.ReadAt(buf, readed)
  439. if err == nil || err == io.EOF {
  440. if n > 0 {
  441. _, err = c.connection.channel.Write(buf[:n])
  442. }
  443. }
  444. readed += int64(n)
  445. if err != nil {
  446. break
  447. }
  448. }
  449. if err != io.EOF {
  450. c.sendErrorMessage(fs, err)
  451. return err
  452. }
  453. err = c.sendConfirmationMessage()
  454. if err != nil {
  455. return err
  456. }
  457. err = c.readConfirmationMessage()
  458. return err
  459. }
  460. func (c *scpCommand) handleDownload(filePath string) error {
  461. c.connection.UpdateLastActivity()
  462. transferQuota := c.connection.GetTransferQuota()
  463. if !transferQuota.HasDownloadSpace() {
  464. c.connection.Log(logger.LevelInfo, "denying file read due to quota limits")
  465. c.sendErrorMessage(nil, c.connection.GetReadQuotaExceededError())
  466. return c.connection.GetReadQuotaExceededError()
  467. }
  468. var err error
  469. fs, p, err := c.connection.GetFsAndResolvedPath(filePath)
  470. if err != nil {
  471. c.connection.Log(logger.LevelError, "error downloading file %q: %+v", filePath, err)
  472. c.sendErrorMessage(nil, fmt.Errorf("unable to download file %q: %w", filePath, err))
  473. return err
  474. }
  475. var stat os.FileInfo
  476. if stat, err = fs.Stat(p); err != nil {
  477. c.connection.Log(logger.LevelError, "error downloading file: %q->%q, err: %v", filePath, p, err)
  478. c.sendErrorMessage(fs, err)
  479. return err
  480. }
  481. if stat.IsDir() {
  482. if !c.connection.User.HasPerm(dataprovider.PermDownload, filePath) {
  483. c.connection.Log(logger.LevelWarn, "error downloading dir: %q, permission denied", filePath)
  484. c.sendErrorMessage(fs, common.ErrPermissionDenied)
  485. return common.ErrPermissionDenied
  486. }
  487. err = c.handleRecursiveDownload(fs, p, filePath, stat)
  488. return err
  489. }
  490. if !c.connection.User.HasPerm(dataprovider.PermDownload, path.Dir(filePath)) {
  491. c.connection.Log(logger.LevelWarn, "error downloading dir: %q, permission denied", filePath)
  492. c.sendErrorMessage(fs, common.ErrPermissionDenied)
  493. return common.ErrPermissionDenied
  494. }
  495. if ok, policy := c.connection.User.IsFileAllowed(filePath); !ok {
  496. c.connection.Log(logger.LevelWarn, "reading file %q is not allowed", filePath)
  497. c.sendErrorMessage(fs, c.connection.GetErrorForDeniedFile(policy))
  498. return common.ErrPermissionDenied
  499. }
  500. if _, err := common.ExecutePreAction(c.connection.BaseConnection, common.OperationPreDownload, p, filePath, 0, 0); err != nil {
  501. c.connection.Log(logger.LevelDebug, "download for file %q denied by pre action: %v", filePath, err)
  502. c.sendErrorMessage(fs, common.ErrPermissionDenied)
  503. return common.ErrPermissionDenied
  504. }
  505. file, r, cancelFn, err := fs.Open(p, 0)
  506. if err != nil {
  507. c.connection.Log(logger.LevelError, "could not open file %q for reading: %v", p, err)
  508. c.sendErrorMessage(fs, err)
  509. return err
  510. }
  511. baseTransfer := common.NewBaseTransfer(file, c.connection.BaseConnection, cancelFn, p, p, filePath,
  512. common.TransferDownload, 0, 0, 0, 0, false, fs, transferQuota)
  513. t := newTransfer(baseTransfer, nil, r, nil)
  514. err = c.sendDownloadFileData(fs, p, stat, t)
  515. // we need to call Close anyway and return close error if any and
  516. // if we have no previous error
  517. if err == nil {
  518. err = t.Close()
  519. } else {
  520. t.TransferError(err)
  521. t.Close()
  522. }
  523. return err
  524. }
  525. func (c *scpCommand) sendFileTime() bool {
  526. return c.hasFlag("p")
  527. }
  528. func (c *scpCommand) isRecursive() bool {
  529. return c.hasFlag("r")
  530. }
  531. func (c *scpCommand) hasFlag(flag string) bool {
  532. for idx := 0; idx < len(c.args)-1; idx++ {
  533. arg := c.args[idx]
  534. if !strings.HasPrefix(arg, "--") && strings.HasPrefix(arg, "-") && strings.Contains(arg, flag) {
  535. return true
  536. }
  537. }
  538. return false
  539. }
  540. // read the SCP confirmation message and the optional text message
  541. // the channel will be closed on errors
  542. func (c *scpCommand) readConfirmationMessage() error {
  543. var msg strings.Builder
  544. buf := make([]byte, 1)
  545. n, err := c.connection.channel.Read(buf)
  546. if err != nil {
  547. c.connection.channel.Close()
  548. return err
  549. }
  550. if n == 1 && (buf[0] == warnMsg[0] || buf[0] == errMsg[0]) {
  551. isError := buf[0] == errMsg[0]
  552. for {
  553. n, err = c.connection.channel.Read(buf)
  554. readed := buf[:n]
  555. if err != nil || (n == 1 && readed[0] == newLine[0]) {
  556. break
  557. }
  558. if n > 0 {
  559. msg.Write(readed)
  560. }
  561. }
  562. c.connection.Log(logger.LevelInfo, "scp error message received: %v is error: %v", msg.String(), isError)
  563. err = fmt.Errorf("%v", msg.String())
  564. c.connection.channel.Close()
  565. }
  566. return err
  567. }
  568. // protool messages are newline terminated
  569. func (c *scpCommand) readProtocolMessage() (string, error) {
  570. var command strings.Builder
  571. var err error
  572. buf := make([]byte, 1)
  573. for {
  574. var n int
  575. n, err = c.connection.channel.Read(buf)
  576. if err != nil {
  577. break
  578. }
  579. if n > 0 {
  580. readed := buf[:n]
  581. if n == 1 && readed[0] == newLine[0] {
  582. break
  583. }
  584. command.Write(readed)
  585. }
  586. }
  587. if err != nil && !errors.Is(err, io.EOF) {
  588. c.connection.channel.Close()
  589. }
  590. return command.String(), err
  591. }
  592. // sendErrorMessage sends an error message and close the channel
  593. // we don't check write errors here, we have to close the channel anyway
  594. //
  595. //nolint:errcheck
  596. func (c *scpCommand) sendErrorMessage(fs vfs.Fs, err error) {
  597. c.connection.channel.Write(errMsg)
  598. if fs != nil {
  599. c.connection.channel.Write([]byte(c.connection.GetFsError(fs, err).Error()))
  600. } else {
  601. c.connection.channel.Write([]byte(err.Error()))
  602. }
  603. c.connection.channel.Write(newLine)
  604. c.connection.channel.Close()
  605. }
  606. // send scp confirmation message and close the channel if an error happen
  607. func (c *scpCommand) sendConfirmationMessage() error {
  608. _, err := c.connection.channel.Write(okMsg)
  609. if err != nil {
  610. c.connection.channel.Close()
  611. }
  612. return err
  613. }
  614. // sends a protocol message and close the channel on error
  615. func (c *scpCommand) sendProtocolMessage(message string) error {
  616. _, err := c.connection.channel.Write([]byte(message))
  617. if err != nil {
  618. c.connection.Log(logger.LevelError, "error sending protocol message: %v, err: %v", message, err)
  619. c.connection.channel.Close()
  620. }
  621. return err
  622. }
  623. // get the next upload protocol message ignoring T command if any
  624. func (c *scpCommand) getNextUploadProtocolMessage() (string, error) {
  625. var command string
  626. var err error
  627. for {
  628. command, err = c.readProtocolMessage()
  629. if err != nil {
  630. return command, err
  631. }
  632. if strings.HasPrefix(command, "T") {
  633. err = c.sendConfirmationMessage()
  634. if err != nil {
  635. return command, err
  636. }
  637. } else {
  638. break
  639. }
  640. }
  641. return command, err
  642. }
  643. func (c *scpCommand) createDir(fs vfs.Fs, dirPath string) error {
  644. err := fs.Mkdir(dirPath)
  645. if err != nil {
  646. c.connection.Log(logger.LevelError, "error creating dir %q: %v", dirPath, err)
  647. c.sendErrorMessage(fs, err)
  648. return err
  649. }
  650. vfs.SetPathPermissions(fs, dirPath, c.connection.User.GetUID(), c.connection.User.GetGID())
  651. return err
  652. }
  653. // parse protocol messages such as:
  654. // D0755 0 testdir
  655. // or:
  656. // C0644 6 testfile
  657. // and returns file size and file/directory name
  658. func (c *scpCommand) parseUploadMessage(fs vfs.Fs, command string) (int64, string, error) {
  659. var size int64
  660. var name string
  661. var err error
  662. if !strings.HasPrefix(command, "C") && !strings.HasPrefix(command, "D") {
  663. err = fmt.Errorf("unknown or invalid upload message: %v args: %v user: %v",
  664. command, c.args, c.connection.User.Username)
  665. c.connection.Log(logger.LevelError, "error: %v", err)
  666. c.sendErrorMessage(fs, err)
  667. return size, name, err
  668. }
  669. parts := strings.SplitN(command, " ", 3)
  670. if len(parts) == 3 {
  671. size, err = strconv.ParseInt(parts[1], 10, 64)
  672. if err != nil {
  673. c.connection.Log(logger.LevelError, "error getting size from upload message: %v", err)
  674. c.sendErrorMessage(fs, err)
  675. return size, name, err
  676. }
  677. name = parts[2]
  678. if name == "" {
  679. err = fmt.Errorf("error getting name from upload message, cannot be empty")
  680. c.connection.Log(logger.LevelError, "error: %v", err)
  681. c.sendErrorMessage(fs, err)
  682. return size, name, err
  683. }
  684. } else {
  685. err = fmt.Errorf("unable to split upload message: %q", command)
  686. c.connection.Log(logger.LevelError, "error: %v", err)
  687. c.sendErrorMessage(fs, err)
  688. return size, name, err
  689. }
  690. return size, name, err
  691. }
  692. func (c *scpCommand) getFileUploadDestPath(fs vfs.Fs, scpDestPath, fileName string) string {
  693. if !c.isRecursive() {
  694. // if the upload is not recursive and the destination path does not end with "/"
  695. // then scpDestPath is the wanted filename, for example:
  696. // scp fileName.txt [email protected]:/newFileName.txt
  697. // or
  698. // scp fileName.txt [email protected]:/fileName.txt
  699. if !strings.HasSuffix(scpDestPath, "/") {
  700. // but if scpDestPath is an existing directory then we put the uploaded file
  701. // inside that directory this is as scp command works, for example:
  702. // scp fileName.txt [email protected]:/existing_dir
  703. if p, err := fs.ResolvePath(scpDestPath); err == nil {
  704. if stat, err := fs.Stat(p); err == nil {
  705. if stat.IsDir() {
  706. return path.Join(scpDestPath, fileName)
  707. }
  708. }
  709. }
  710. return scpDestPath
  711. }
  712. }
  713. // if the upload is recursive or scpDestPath has the "/" suffix then the destination
  714. // file is relative to scpDestPath
  715. return path.Join(scpDestPath, fileName)
  716. }
  717. func getFileModeAsString(fileMode os.FileMode, isDir bool) string {
  718. var defaultMode string
  719. if isDir {
  720. defaultMode = "0755"
  721. } else {
  722. defaultMode = "0644"
  723. }
  724. if fileMode == 0 {
  725. return defaultMode
  726. }
  727. modeString := []byte(fileMode.String())
  728. nullPerm := []byte("-")
  729. u := 0
  730. g := 0
  731. o := 0
  732. s := 0
  733. lastChar := len(modeString) - 1
  734. if fileMode&os.ModeSticky != 0 {
  735. s++
  736. }
  737. if fileMode&os.ModeSetuid != 0 {
  738. s += 2
  739. }
  740. if fileMode&os.ModeSetgid != 0 {
  741. s += 4
  742. }
  743. if modeString[lastChar-8] != nullPerm[0] {
  744. u += 4
  745. }
  746. if modeString[lastChar-7] != nullPerm[0] {
  747. u += 2
  748. }
  749. if modeString[lastChar-6] != nullPerm[0] {
  750. u++
  751. }
  752. if modeString[lastChar-5] != nullPerm[0] {
  753. g += 4
  754. }
  755. if modeString[lastChar-4] != nullPerm[0] {
  756. g += 2
  757. }
  758. if modeString[lastChar-3] != nullPerm[0] {
  759. g++
  760. }
  761. if modeString[lastChar-2] != nullPerm[0] {
  762. o += 4
  763. }
  764. if modeString[lastChar-1] != nullPerm[0] {
  765. o += 2
  766. }
  767. if modeString[lastChar] != nullPerm[0] {
  768. o++
  769. }
  770. return fmt.Sprintf("%v%v%v%v", s, u, g, o)
  771. }