samba.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package samba
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strings"
  7. )
  8. /*
  9. Samba Share Warpper
  10. Note that this module only provide exposing of local disk / storage.
  11. This module do not handle providing the virtualized interface for samba
  12. */
  13. type SambaConfigEditor struct {
  14. SambaConfigPath string
  15. }
  16. // AppendSambaShareConfig appends the Samba share configuration to smb.conf
  17. func (s *SambaConfigEditor) AppendSambaShareConfig(config string) error {
  18. file, err := os.OpenFile("/etc/samba/smb.conf", os.O_APPEND|os.O_WRONLY, 0644)
  19. if err != nil {
  20. return err
  21. }
  22. defer file.Close()
  23. if _, err := file.WriteString(config); err != nil {
  24. return err
  25. }
  26. return nil
  27. }
  28. // RemoveSambaShareConfig removes the Samba share configuration from smb.conf
  29. func (s *SambaConfigEditor) RemoveSambaShareConfig(shareName string) error {
  30. // Open the smb.conf file for reading
  31. file, err := os.Open("/etc/samba/smb.conf")
  32. if err != nil {
  33. return err
  34. }
  35. defer file.Close()
  36. // Create a temporary file to store modified smb.conf
  37. tmpFile, err := os.CreateTemp("", "smb.conf.*.tmp")
  38. if err != nil {
  39. return err
  40. }
  41. defer tmpFile.Close()
  42. // Create a scanner to read the smb.conf file line by line
  43. scanner := bufio.NewScanner(file)
  44. for scanner.Scan() {
  45. line := scanner.Text()
  46. // Check if the line contains the share name
  47. if strings.HasPrefix(line, "["+shareName+"]") {
  48. // Skip the lines until the next section
  49. for scanner.Scan() {
  50. if strings.HasPrefix(scanner.Text(), "[") {
  51. break
  52. }
  53. }
  54. continue // Skip writing the share configuration to the temporary file
  55. }
  56. // Write the line to the temporary file
  57. _, err := fmt.Fprintln(tmpFile, line)
  58. if err != nil {
  59. return err
  60. }
  61. }
  62. // Check for scanner errors
  63. if err := scanner.Err(); err != nil {
  64. return err
  65. }
  66. // Close the original smb.conf file
  67. if err := file.Close(); err != nil {
  68. return err
  69. }
  70. // Close the temporary file
  71. if err := tmpFile.Close(); err != nil {
  72. return err
  73. }
  74. // Replace the original smb.conf file with the temporary file
  75. if err := os.Rename(tmpFile.Name(), "/etc/samba/smb.conf"); err != nil {
  76. return err
  77. }
  78. return nil
  79. }