samba.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package samba
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "time"
  12. "imuslab.com/arozos/mod/utils"
  13. )
  14. /*
  15. Samba Share Warpper
  16. Note that this module only provide exposing of local disk / storage.
  17. This module do not handle providing the virtualized interface for samba
  18. */
  19. type ShareManager struct {
  20. SambaConfigPath string //Config file for samba, aka smb.conf
  21. BackupDir string //Backup directory for restoring previous config
  22. }
  23. type ShareConfig struct {
  24. Name string
  25. Path string
  26. ValidUsers []string
  27. ReadOnly bool
  28. Browseable bool
  29. GuestOk bool
  30. }
  31. func NewSambaShareManager() (*ShareManager, error) {
  32. if runtime.GOOS == "linux" {
  33. //Check if samba installed
  34. if !utils.FileExists("/bin/smbcontrol") {
  35. return nil, errors.New("samba not installed")
  36. }
  37. } else {
  38. return nil, errors.New("platform not supported")
  39. }
  40. return &ShareManager{
  41. SambaConfigPath: "/etc/samba/smb.conf",
  42. BackupDir: "./backup",
  43. }, nil
  44. }
  45. // ReadSambaShares reads the smb.conf file and extracts all existing shares
  46. func (s *ShareManager) ReadSambaShares() ([]ShareConfig, error) {
  47. file, err := os.Open(s.SambaConfigPath)
  48. if err != nil {
  49. return nil, err
  50. }
  51. defer file.Close()
  52. var shares []ShareConfig
  53. var currentShare *ShareConfig
  54. scanner := bufio.NewScanner(file)
  55. for scanner.Scan() {
  56. line := strings.TrimSpace(scanner.Text())
  57. // Check for section headers
  58. if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
  59. if currentShare != nil {
  60. shares = append(shares, *currentShare)
  61. }
  62. currentShare = &ShareConfig{
  63. Name: strings.Trim(line, "[]"),
  64. }
  65. continue
  66. }
  67. // Check if we are currently processing a share section
  68. if currentShare != nil {
  69. tokens := strings.SplitN(line, "=", 2)
  70. if len(tokens) != 2 {
  71. continue
  72. }
  73. key := strings.TrimSpace(tokens[0])
  74. value := strings.TrimSpace(tokens[1])
  75. switch key {
  76. case "path":
  77. currentShare.Path = value
  78. case "valid users":
  79. currentShare.ValidUsers = strings.Fields(value)
  80. case "read only":
  81. currentShare.ReadOnly = (value == "yes")
  82. case "browseable":
  83. currentShare.Browseable = (value == "yes")
  84. case "guest ok":
  85. currentShare.GuestOk = (value == "yes")
  86. }
  87. }
  88. }
  89. // Add the last share if there is one
  90. if currentShare != nil {
  91. shares = append(shares, *currentShare)
  92. }
  93. // Check for scanner errors
  94. if err := scanner.Err(); err != nil {
  95. return nil, err
  96. }
  97. return shares, nil
  98. }
  99. // CreateNewSambaShare converts the shareConfig to string and appends it to smb.conf if the share name does not already exist
  100. func (s *ShareManager) CreateNewSambaShare(shareToCreate *ShareConfig) error {
  101. // Path to smb.conf
  102. smbConfPath := s.SambaConfigPath
  103. // Open the smb.conf file for reading
  104. file, err := os.Open(smbConfPath)
  105. if err != nil {
  106. return fmt.Errorf("failed to open smb.conf: %v", err)
  107. }
  108. defer file.Close()
  109. // Check if the share already exists
  110. scanner := bufio.NewScanner(file)
  111. shareExists := false
  112. shareNameSection := fmt.Sprintf("[%s]", shareToCreate.Name)
  113. for scanner.Scan() {
  114. if strings.TrimSpace(scanner.Text()) == shareNameSection {
  115. shareExists = true
  116. break
  117. }
  118. }
  119. if err := scanner.Err(); err != nil {
  120. return fmt.Errorf("failed to read smb.conf: %v", err)
  121. }
  122. if shareExists {
  123. return fmt.Errorf("share %s already exists", shareToCreate.Name)
  124. }
  125. // Convert ShareConfig to string
  126. shareConfigString := convertShareConfigToString(shareToCreate)
  127. // Open the smb.conf file for appending
  128. file, err = os.OpenFile(smbConfPath, os.O_APPEND|os.O_WRONLY, 0644)
  129. if err != nil {
  130. return fmt.Errorf("failed to open smb.conf for writing: %v", err)
  131. }
  132. defer file.Close()
  133. // Append the new share configuration
  134. if _, err := file.WriteString(shareConfigString); err != nil {
  135. return fmt.Errorf("failed to write to smb.conf: %v", err)
  136. }
  137. return nil
  138. }
  139. // RemoveSambaShareConfig removes the Samba share configuration from smb.conf
  140. func (s *ShareManager) RemoveSambaShareConfig(shareName string) error {
  141. // Open the smb.conf file for reading
  142. file, err := os.Open(s.SambaConfigPath)
  143. if err != nil {
  144. return err
  145. }
  146. defer file.Close()
  147. // Create a temporary file to store modified smb.conf
  148. tmpFile, err := os.CreateTemp("", "smb.conf.*.tmp")
  149. if err != nil {
  150. return err
  151. }
  152. defer tmpFile.Close()
  153. // Create a scanner to read the smb.conf file line by line
  154. scanner := bufio.NewScanner(file)
  155. for scanner.Scan() {
  156. line := scanner.Text()
  157. // Check if the line contains the share name
  158. if strings.HasPrefix(line, "["+shareName+"]") {
  159. // Skip the lines until the next section
  160. for scanner.Scan() {
  161. if strings.HasPrefix(scanner.Text(), "[") {
  162. break
  163. }
  164. }
  165. continue // Skip writing the share configuration to the temporary file
  166. }
  167. // Write the line to the temporary file
  168. _, err := fmt.Fprintln(tmpFile, line)
  169. if err != nil {
  170. return err
  171. }
  172. }
  173. // Check for scanner errors
  174. if err := scanner.Err(); err != nil {
  175. return err
  176. }
  177. // Close the original smb.conf file
  178. if err := file.Close(); err != nil {
  179. return err
  180. }
  181. // Close the temporary file
  182. if err := tmpFile.Close(); err != nil {
  183. return err
  184. }
  185. // Replace the original smb.conf file with the temporary file
  186. if err := os.Rename(tmpFile.Name(), "/etc/samba/smb.conf"); err != nil {
  187. return err
  188. }
  189. return nil
  190. }
  191. // ShareExists checks if a given share name exists in smb.conf
  192. func (s *ShareManager) ShareExists(shareName string) (bool, error) {
  193. // Path to smb.conf
  194. smbConfPath := s.SambaConfigPath
  195. // Open the smb.conf file for reading
  196. file, err := os.Open(smbConfPath)
  197. if err != nil {
  198. return false, fmt.Errorf("failed to open smb.conf: %v", err)
  199. }
  200. defer file.Close()
  201. // Check if the share already exists
  202. scanner := bufio.NewScanner(file)
  203. shareNameSection := fmt.Sprintf("[%s]", shareName)
  204. for scanner.Scan() {
  205. if strings.TrimSpace(scanner.Text()) == shareNameSection {
  206. return true, nil
  207. }
  208. }
  209. if err := scanner.Err(); err != nil {
  210. return false, fmt.Errorf("failed to read smb.conf: %v", err)
  211. }
  212. return false, nil
  213. }
  214. // Backup the current smb.conf to the backup folder
  215. func (s *ShareManager) BackupSmbConf() error {
  216. // Define source and backup directory
  217. sourceFile := s.SambaConfigPath
  218. backupDir := s.BackupDir
  219. // Ensure the backup directory exists
  220. err := os.MkdirAll(backupDir, 0755)
  221. if err != nil {
  222. return fmt.Errorf("failed to create backup directory: %v", err)
  223. }
  224. // Create a timestamped backup filename
  225. timestamp := time.Now().Format("20060102_150405")
  226. backupFile := filepath.Join(backupDir, fmt.Sprintf("%s.smb.conf", timestamp))
  227. // Open the source file
  228. src, err := os.Open(sourceFile)
  229. if err != nil {
  230. return fmt.Errorf("failed to open source file: %v", err)
  231. }
  232. defer src.Close()
  233. // Create the destination file
  234. dst, err := os.Create(backupFile)
  235. if err != nil {
  236. return fmt.Errorf("failed to create backup file: %v", err)
  237. }
  238. defer dst.Close()
  239. // Copy the contents of the source file to the backup file
  240. _, err = io.Copy(dst, src)
  241. if err != nil {
  242. return fmt.Errorf("failed to copy file contents: %v", err)
  243. }
  244. return nil
  245. }