scp.go 21 KB

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