scp.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. package sftpd
  2. import (
  3. "fmt"
  4. "io"
  5. "math"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "runtime/debug"
  10. "strconv"
  11. "strings"
  12. "github.com/drakkan/sftpgo/common"
  13. "github.com/drakkan/sftpgo/dataprovider"
  14. "github.com/drakkan/sftpgo/logger"
  15. "github.com/drakkan/sftpgo/utils"
  16. "github.com/drakkan/sftpgo/vfs"
  17. )
  18. var (
  19. okMsg = []byte{0x00}
  20. warnMsg = []byte{0x01} // must be followed by an optional message and a newline
  21. errMsg = []byte{0x02} // must be followed by an optional message and a newline
  22. newLine = []byte{0x0A}
  23. )
  24. type scpCommand struct {
  25. sshCommand
  26. }
  27. func (c *scpCommand) handle() (err error) {
  28. defer func() {
  29. if r := recover(); r != nil {
  30. logger.Error(logSender, "", "panic in handle scp command: %#v stack strace: %v", r, string(debug.Stack()))
  31. err = common.ErrGenericFailure
  32. }
  33. }()
  34. common.Connections.Add(c.connection)
  35. defer common.Connections.Remove(c.connection.GetID())
  36. destPath := c.getDestPath()
  37. commandType := c.getCommandType()
  38. c.connection.Log(logger.LevelDebug, "handle scp command, args: %v user: %v command type: %v, dest path: %#v",
  39. c.args, c.connection.User.Username, commandType, destPath)
  40. if commandType == "-t" {
  41. // -t means "to", so upload
  42. err = c.handleRecursiveUpload()
  43. if err != nil {
  44. return err
  45. }
  46. } else if commandType == "-f" {
  47. // -f means "from" so download
  48. err = c.readConfirmationMessage()
  49. if err != nil {
  50. return err
  51. }
  52. err = c.handleDownload(destPath)
  53. if err != nil {
  54. return err
  55. }
  56. } else {
  57. err = fmt.Errorf("scp command not supported, args: %v", c.args)
  58. c.connection.Log(logger.LevelDebug, "unsupported scp command, args: %v", c.args)
  59. }
  60. c.sendExitStatus(err)
  61. return err
  62. }
  63. func (c *scpCommand) handleRecursiveUpload() error {
  64. var err error
  65. numDirs := 0
  66. destPath := c.getDestPath()
  67. for {
  68. err = c.sendConfirmationMessage()
  69. if err != nil {
  70. return err
  71. }
  72. command, err := c.getNextUploadProtocolMessage()
  73. if err != nil {
  74. return err
  75. }
  76. if strings.HasPrefix(command, "E") {
  77. numDirs--
  78. c.connection.Log(logger.LevelDebug, "received end dir command, num dirs: %v", numDirs)
  79. if numDirs == 0 {
  80. // upload is now complete send confirmation message
  81. err = c.sendConfirmationMessage()
  82. if err != nil {
  83. return err
  84. }
  85. } else {
  86. // the destination dir is now the parent directory
  87. destPath = path.Join(destPath, "..")
  88. }
  89. } else {
  90. sizeToRead, name, err := c.parseUploadMessage(command)
  91. if err != nil {
  92. return err
  93. }
  94. if strings.HasPrefix(command, "D") {
  95. numDirs++
  96. destPath = path.Join(destPath, name)
  97. err = c.handleCreateDir(destPath)
  98. if err != nil {
  99. return err
  100. }
  101. c.connection.Log(logger.LevelDebug, "received start dir command, num dirs: %v destPath: %#v", numDirs, destPath)
  102. } else if strings.HasPrefix(command, "C") {
  103. err = c.handleUpload(c.getFileUploadDestPath(destPath, name), sizeToRead)
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. }
  109. if err != nil || numDirs == 0 {
  110. break
  111. }
  112. }
  113. return err
  114. }
  115. func (c *scpCommand) handleCreateDir(dirPath string) error {
  116. c.connection.UpdateLastActivity()
  117. p, err := c.connection.Fs.ResolvePath(dirPath)
  118. if err != nil {
  119. c.connection.Log(logger.LevelWarn, "error creating dir: %#v, invalid file path, err: %v", dirPath, err)
  120. c.sendErrorMessage(err)
  121. return err
  122. }
  123. if !c.connection.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(dirPath)) {
  124. c.connection.Log(logger.LevelWarn, "error creating dir: %#v, permission denied", dirPath)
  125. c.sendErrorMessage(common.ErrPermissionDenied)
  126. return common.ErrPermissionDenied
  127. }
  128. err = c.createDir(p)
  129. if err != nil {
  130. return err
  131. }
  132. c.connection.Log(logger.LevelDebug, "created dir %#v", dirPath)
  133. return nil
  134. }
  135. // we need to close the transfer if we have an error
  136. func (c *scpCommand) getUploadFileData(sizeToRead int64, transfer *transfer) error {
  137. err := c.sendConfirmationMessage()
  138. if err != nil {
  139. transfer.TransferError(err)
  140. transfer.Close()
  141. return err
  142. }
  143. if sizeToRead > 0 {
  144. remaining := sizeToRead
  145. buf := make([]byte, int64(math.Min(32768, float64(sizeToRead))))
  146. for {
  147. n, err := c.connection.channel.Read(buf)
  148. if err != nil {
  149. c.sendErrorMessage(err)
  150. transfer.TransferError(err)
  151. transfer.Close()
  152. return err
  153. }
  154. _, err = transfer.WriteAt(buf[:n], sizeToRead-remaining)
  155. if err != nil {
  156. c.sendErrorMessage(err)
  157. transfer.Close()
  158. return err
  159. }
  160. remaining -= int64(n)
  161. if remaining <= 0 {
  162. break
  163. }
  164. if remaining < int64(len(buf)) {
  165. buf = make([]byte, remaining)
  166. }
  167. }
  168. }
  169. err = c.readConfirmationMessage()
  170. if err != nil {
  171. transfer.TransferError(err)
  172. transfer.Close()
  173. return err
  174. }
  175. err = transfer.Close()
  176. if err != nil {
  177. c.sendErrorMessage(err)
  178. return err
  179. }
  180. return c.sendConfirmationMessage()
  181. }
  182. func (c *scpCommand) handleUploadFile(resolvedPath, filePath string, sizeToRead int64, isNewFile bool, fileSize int64, requestPath string) error {
  183. quotaResult := c.connection.HasSpace(isNewFile, requestPath)
  184. if !quotaResult.HasSpace {
  185. err := fmt.Errorf("denying file write due to quota limits")
  186. c.connection.Log(logger.LevelWarn, "error uploading file: %#v, err: %v", filePath, err)
  187. c.sendErrorMessage(err)
  188. return err
  189. }
  190. maxWriteSize, _ := c.connection.GetMaxWriteSize(quotaResult, false, fileSize)
  191. file, w, cancelFn, err := c.connection.Fs.Create(filePath, 0)
  192. if err != nil {
  193. c.connection.Log(logger.LevelError, "error creating file %#v: %v", resolvedPath, err)
  194. c.sendErrorMessage(err)
  195. return err
  196. }
  197. initialSize := int64(0)
  198. if !isNewFile {
  199. if vfs.IsLocalOsFs(c.connection.Fs) {
  200. vfolder, err := c.connection.User.GetVirtualFolderForPath(path.Dir(requestPath))
  201. if err == nil {
  202. dataprovider.UpdateVirtualFolderQuota(vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  203. if vfolder.IsIncludedInUserQuota() {
  204. dataprovider.UpdateUserQuota(c.connection.User, 0, -fileSize, false) //nolint:errcheck
  205. }
  206. } else {
  207. dataprovider.UpdateUserQuota(c.connection.User, 0, -fileSize, false) //nolint:errcheck
  208. }
  209. } else {
  210. initialSize = fileSize
  211. }
  212. if maxWriteSize > 0 {
  213. maxWriteSize += fileSize
  214. }
  215. }
  216. vfs.SetPathPermissions(c.connection.Fs, filePath, c.connection.User.GetUID(), c.connection.User.GetGID())
  217. baseTransfer := common.NewBaseTransfer(file, c.connection.BaseConnection, cancelFn, resolvedPath, requestPath,
  218. common.TransferUpload, 0, initialSize, maxWriteSize, isNewFile, c.connection.Fs)
  219. t := newTransfer(baseTransfer, w, nil, nil)
  220. return c.getUploadFileData(sizeToRead, t)
  221. }
  222. func (c *scpCommand) handleUpload(uploadFilePath string, sizeToRead int64) error {
  223. c.connection.UpdateLastActivity()
  224. var err error
  225. if !c.connection.User.IsFileAllowed(uploadFilePath) {
  226. c.connection.Log(logger.LevelWarn, "writing file %#v is not allowed", uploadFilePath)
  227. c.sendErrorMessage(common.ErrPermissionDenied)
  228. return common.ErrPermissionDenied
  229. }
  230. p, err := c.connection.Fs.ResolvePath(uploadFilePath)
  231. if err != nil {
  232. c.connection.Log(logger.LevelWarn, "error uploading file: %#v, err: %v", uploadFilePath, err)
  233. c.sendErrorMessage(err)
  234. return err
  235. }
  236. filePath := p
  237. if common.Config.IsAtomicUploadEnabled() && c.connection.Fs.IsAtomicUploadSupported() {
  238. filePath = c.connection.Fs.GetAtomicUploadPath(p)
  239. }
  240. stat, statErr := c.connection.Fs.Lstat(p)
  241. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || c.connection.Fs.IsNotExist(statErr) {
  242. if !c.connection.User.HasPerm(dataprovider.PermUpload, path.Dir(uploadFilePath)) {
  243. c.connection.Log(logger.LevelWarn, "cannot upload file: %#v, permission denied", uploadFilePath)
  244. c.sendErrorMessage(common.ErrPermissionDenied)
  245. return common.ErrPermissionDenied
  246. }
  247. return c.handleUploadFile(p, filePath, sizeToRead, true, 0, uploadFilePath)
  248. }
  249. if statErr != nil {
  250. c.connection.Log(logger.LevelError, "error performing file stat %#v: %v", p, statErr)
  251. c.sendErrorMessage(statErr)
  252. return statErr
  253. }
  254. if stat.IsDir() {
  255. c.connection.Log(logger.LevelWarn, "attempted to open a directory for writing to: %#v", p)
  256. err = fmt.Errorf("Attempted to open a directory for writing: %#v", p)
  257. c.sendErrorMessage(err)
  258. return err
  259. }
  260. if !c.connection.User.HasPerm(dataprovider.PermOverwrite, uploadFilePath) {
  261. c.connection.Log(logger.LevelWarn, "cannot overwrite file: %#v, permission denied", uploadFilePath)
  262. c.sendErrorMessage(common.ErrPermissionDenied)
  263. return common.ErrPermissionDenied
  264. }
  265. if common.Config.IsAtomicUploadEnabled() && c.connection.Fs.IsAtomicUploadSupported() {
  266. err = c.connection.Fs.Rename(p, filePath)
  267. if err != nil {
  268. c.connection.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %v",
  269. p, filePath, err)
  270. c.sendErrorMessage(err)
  271. return err
  272. }
  273. }
  274. return c.handleUploadFile(p, filePath, sizeToRead, false, stat.Size(), uploadFilePath)
  275. }
  276. func (c *scpCommand) sendDownloadProtocolMessages(dirPath string, stat os.FileInfo) error {
  277. var err error
  278. if c.sendFileTime() {
  279. modTime := stat.ModTime().UnixNano() / 1000000000
  280. tCommand := fmt.Sprintf("T%v 0 %v 0\n", modTime, modTime)
  281. err = c.sendProtocolMessage(tCommand)
  282. if err != nil {
  283. return err
  284. }
  285. err = c.readConfirmationMessage()
  286. if err != nil {
  287. return err
  288. }
  289. }
  290. dirName := filepath.Base(dirPath)
  291. for _, v := range c.connection.User.VirtualFolders {
  292. if v.MappedPath == dirPath {
  293. dirName = path.Base(v.VirtualPath)
  294. break
  295. }
  296. }
  297. fileMode := fmt.Sprintf("D%v 0 %v\n", getFileModeAsString(stat.Mode(), stat.IsDir()), dirName)
  298. err = c.sendProtocolMessage(fileMode)
  299. if err != nil {
  300. return err
  301. }
  302. err = c.readConfirmationMessage()
  303. return err
  304. }
  305. // We send first all the files in the root directory and then the directories.
  306. // For each directory we recursively call this method again
  307. func (c *scpCommand) handleRecursiveDownload(dirPath string, stat os.FileInfo) error {
  308. var err error
  309. if c.isRecursive() {
  310. c.connection.Log(logger.LevelDebug, "recursive download, dir path: %#v", dirPath)
  311. err = c.sendDownloadProtocolMessages(dirPath, stat)
  312. if err != nil {
  313. return err
  314. }
  315. files, err := c.connection.Fs.ReadDir(dirPath)
  316. files = c.connection.User.AddVirtualDirs(files, c.connection.Fs.GetRelativePath(dirPath))
  317. if err != nil {
  318. c.sendErrorMessage(err)
  319. return err
  320. }
  321. var dirs []string
  322. for _, file := range files {
  323. filePath := c.connection.Fs.GetRelativePath(c.connection.Fs.Join(dirPath, file.Name()))
  324. if file.Mode().IsRegular() || file.Mode()&os.ModeSymlink != 0 {
  325. err = c.handleDownload(filePath)
  326. if err != nil {
  327. break
  328. }
  329. } else if file.IsDir() {
  330. dirs = append(dirs, filePath)
  331. }
  332. }
  333. if err != nil {
  334. c.sendErrorMessage(err)
  335. return err
  336. }
  337. for _, dir := range dirs {
  338. err = c.handleDownload(dir)
  339. if err != nil {
  340. break
  341. }
  342. }
  343. if err != nil {
  344. c.sendErrorMessage(err)
  345. return err
  346. }
  347. err = c.sendProtocolMessage("E\n")
  348. if err != nil {
  349. return err
  350. }
  351. err = c.readConfirmationMessage()
  352. if err != nil {
  353. return err
  354. }
  355. return err
  356. }
  357. err = fmt.Errorf("Unable to send directory for non recursive copy")
  358. c.sendErrorMessage(err)
  359. return err
  360. }
  361. func (c *scpCommand) sendDownloadFileData(filePath string, stat os.FileInfo, transfer *transfer) error {
  362. var err error
  363. if c.sendFileTime() {
  364. modTime := stat.ModTime().UnixNano() / 1000000000
  365. tCommand := fmt.Sprintf("T%v 0 %v 0\n", modTime, modTime)
  366. err = c.sendProtocolMessage(tCommand)
  367. if err != nil {
  368. return err
  369. }
  370. err = c.readConfirmationMessage()
  371. if err != nil {
  372. return err
  373. }
  374. }
  375. if vfs.IsCryptOsFs(c.connection.Fs) {
  376. stat = c.connection.Fs.(*vfs.CryptFs).ConvertFileInfo(stat)
  377. }
  378. fileSize := stat.Size()
  379. readed := int64(0)
  380. fileMode := fmt.Sprintf("C%v %v %v\n", getFileModeAsString(stat.Mode(), stat.IsDir()), fileSize, filepath.Base(filePath))
  381. err = c.sendProtocolMessage(fileMode)
  382. if err != nil {
  383. return err
  384. }
  385. err = c.readConfirmationMessage()
  386. if err != nil {
  387. return err
  388. }
  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.WriteString(string(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.WriteString(string(readed))
  523. }
  524. }
  525. if err != nil {
  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. // we use our own user setting for permissions
  557. func (c *scpCommand) getNextUploadProtocolMessage() (string, error) {
  558. var command string
  559. var err error
  560. for {
  561. command, err = c.readProtocolMessage()
  562. if err != nil {
  563. return command, err
  564. }
  565. if strings.HasPrefix(command, "T") {
  566. err = c.sendConfirmationMessage()
  567. if err != nil {
  568. return command, err
  569. }
  570. } else {
  571. break
  572. }
  573. }
  574. return command, err
  575. }
  576. func (c *scpCommand) createDir(dirPath string) error {
  577. var err error
  578. var isDir bool
  579. isDir, err = vfs.IsDirectory(c.connection.Fs, dirPath)
  580. if err == nil && isDir {
  581. c.connection.Log(logger.LevelDebug, "directory %#v already exists", dirPath)
  582. return nil
  583. }
  584. if err = c.connection.Fs.Mkdir(dirPath); err != nil {
  585. c.connection.Log(logger.LevelError, "error creating dir %#v: %v", dirPath, err)
  586. c.sendErrorMessage(err)
  587. return err
  588. }
  589. vfs.SetPathPermissions(c.connection.Fs, dirPath, c.connection.User.GetUID(), c.connection.User.GetGID())
  590. return err
  591. }
  592. // parse protocol messages such as:
  593. // D0755 0 testdir
  594. // or:
  595. // C0644 6 testfile
  596. // and returns file size and file/directory name
  597. func (c *scpCommand) parseUploadMessage(command string) (int64, string, error) {
  598. var size int64
  599. var name string
  600. var err error
  601. if !strings.HasPrefix(command, "C") && !strings.HasPrefix(command, "D") {
  602. err = fmt.Errorf("unknown or invalid upload message: %v args: %v user: %v",
  603. command, c.args, c.connection.User.Username)
  604. c.connection.Log(logger.LevelWarn, "error: %v", err)
  605. c.sendErrorMessage(err)
  606. return size, name, err
  607. }
  608. parts := strings.SplitN(command, " ", 3)
  609. if len(parts) == 3 {
  610. size, err = strconv.ParseInt(parts[1], 10, 64)
  611. if err != nil {
  612. c.connection.Log(logger.LevelWarn, "error getting size from upload message: %v", err)
  613. c.sendErrorMessage(err)
  614. return size, name, err
  615. }
  616. name = parts[2]
  617. if len(name) == 0 {
  618. err = fmt.Errorf("error getting name from upload message, cannot be empty")
  619. c.connection.Log(logger.LevelWarn, "error: %v", err)
  620. c.sendErrorMessage(err)
  621. return size, name, err
  622. }
  623. } else {
  624. err = fmt.Errorf("Error splitting upload message: %#v", command)
  625. c.connection.Log(logger.LevelWarn, "error: %v", err)
  626. c.sendErrorMessage(err)
  627. return size, name, err
  628. }
  629. return size, name, err
  630. }
  631. func (c *scpCommand) getFileUploadDestPath(scpDestPath, fileName string) string {
  632. if !c.isRecursive() {
  633. // if the upload is not recursive and the destination path does not end with "/"
  634. // then scpDestPath is the wanted filename, for example:
  635. // scp fileName.txt [email protected]:/newFileName.txt
  636. // or
  637. // scp fileName.txt [email protected]:/fileName.txt
  638. if !strings.HasSuffix(scpDestPath, "/") {
  639. // but if scpDestPath is an existing directory then we put the uploaded file
  640. // inside that directory this is as scp command works, for example:
  641. // scp fileName.txt [email protected]:/existing_dir
  642. if p, err := c.connection.Fs.ResolvePath(scpDestPath); err == nil {
  643. if stat, err := c.connection.Fs.Stat(p); err == nil {
  644. if stat.IsDir() {
  645. return path.Join(scpDestPath, fileName)
  646. }
  647. }
  648. }
  649. return scpDestPath
  650. }
  651. }
  652. // if the upload is recursive or scpDestPath has the "/" suffix then the destination
  653. // file is relative to scpDestPath
  654. return path.Join(scpDestPath, fileName)
  655. }
  656. func getFileModeAsString(fileMode os.FileMode, isDir bool) string {
  657. var defaultMode string
  658. if isDir {
  659. defaultMode = "0755"
  660. } else {
  661. defaultMode = "0644"
  662. }
  663. if fileMode == 0 {
  664. return defaultMode
  665. }
  666. modeString := []byte(fileMode.String())
  667. nullPerm := []byte("-")
  668. u := 0
  669. g := 0
  670. o := 0
  671. s := 0
  672. lastChar := len(modeString) - 1
  673. if fileMode&os.ModeSticky != 0 {
  674. s++
  675. }
  676. if fileMode&os.ModeSetuid != 0 {
  677. s += 2
  678. }
  679. if fileMode&os.ModeSetgid != 0 {
  680. s += 4
  681. }
  682. if modeString[lastChar-8] != nullPerm[0] {
  683. u += 4
  684. }
  685. if modeString[lastChar-7] != nullPerm[0] {
  686. u += 2
  687. }
  688. if modeString[lastChar-6] != nullPerm[0] {
  689. u++
  690. }
  691. if modeString[lastChar-5] != nullPerm[0] {
  692. g += 4
  693. }
  694. if modeString[lastChar-4] != nullPerm[0] {
  695. g += 2
  696. }
  697. if modeString[lastChar-3] != nullPerm[0] {
  698. g++
  699. }
  700. if modeString[lastChar-2] != nullPerm[0] {
  701. o += 4
  702. }
  703. if modeString[lastChar-1] != nullPerm[0] {
  704. o += 2
  705. }
  706. if modeString[lastChar] != nullPerm[0] {
  707. o++
  708. }
  709. return fmt.Sprintf("%v%v%v%v", s, u, g, o)
  710. }