scp.go 21 KB

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