scp.go 22 KB

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