samba.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. // A basic filter to remove system created smb shares entry in the list
  100. func (s *ShareManager) FilterSystemCreatedShares(shares []ShareConfig) []ShareConfig {
  101. namesToRemove := []string{"global", "homes", "printers", "print$"}
  102. filteredShares := []ShareConfig{}
  103. for _, share := range shares {
  104. if !utils.StringInArray(namesToRemove, share.Name) {
  105. filteredShares = append(filteredShares, share)
  106. }
  107. }
  108. return filteredShares
  109. }
  110. // CreateNewSambaShare converts the shareConfig to string and appends it to smb.conf if the share name does not already exist
  111. func (s *ShareManager) CreateNewSambaShare(shareToCreate *ShareConfig) error {
  112. // Path to smb.conf
  113. smbConfPath := s.SambaConfigPath
  114. // Open the smb.conf file for reading
  115. file, err := os.Open(smbConfPath)
  116. if err != nil {
  117. return fmt.Errorf("failed to open smb.conf: %v", err)
  118. }
  119. defer file.Close()
  120. // Check if the share already exists
  121. scanner := bufio.NewScanner(file)
  122. shareExists := false
  123. shareNameSection := fmt.Sprintf("[%s]", shareToCreate.Name)
  124. for scanner.Scan() {
  125. if strings.TrimSpace(scanner.Text()) == shareNameSection {
  126. shareExists = true
  127. break
  128. }
  129. }
  130. if err := scanner.Err(); err != nil {
  131. return fmt.Errorf("failed to read smb.conf: %v", err)
  132. }
  133. if shareExists {
  134. return fmt.Errorf("share %s already exists", shareToCreate.Name)
  135. }
  136. // Convert ShareConfig to string
  137. shareConfigString := convertShareConfigToString(shareToCreate)
  138. // Open the smb.conf file for appending
  139. file, err = os.OpenFile(smbConfPath, os.O_APPEND|os.O_WRONLY, 0644)
  140. if err != nil {
  141. return fmt.Errorf("failed to open smb.conf for writing: %v", err)
  142. }
  143. defer file.Close()
  144. // Append the new share configuration
  145. if _, err := file.WriteString(shareConfigString); err != nil {
  146. return fmt.Errorf("failed to write to smb.conf: %v", err)
  147. }
  148. return nil
  149. }
  150. // RemoveSambaShareConfig removes the Samba share configuration from smb.conf
  151. func (s *ShareManager) RemoveSambaShareConfig(shareName string) error {
  152. // Open the smb.conf file for reading
  153. file, err := os.Open(s.SambaConfigPath)
  154. if err != nil {
  155. return err
  156. }
  157. defer file.Close()
  158. // Create a temporary file to store modified smb.conf
  159. tmpFile, err := os.CreateTemp("", "smb.conf.*.tmp")
  160. if err != nil {
  161. return err
  162. }
  163. defer tmpFile.Close()
  164. // Create a scanner to read the smb.conf file line by line
  165. scanner := bufio.NewScanner(file)
  166. for scanner.Scan() {
  167. line := scanner.Text()
  168. // Check if the line contains the share name
  169. if strings.HasPrefix(line, "["+shareName+"]") {
  170. // Skip the lines until the next section
  171. for scanner.Scan() {
  172. if strings.HasPrefix(scanner.Text(), "[") {
  173. break
  174. }
  175. }
  176. continue // Skip writing the share configuration to the temporary file
  177. }
  178. // Write the line to the temporary file
  179. _, err := fmt.Fprintln(tmpFile, line)
  180. if err != nil {
  181. return err
  182. }
  183. }
  184. // Check for scanner errors
  185. if err := scanner.Err(); err != nil {
  186. return err
  187. }
  188. // Close the original smb.conf file
  189. if err := file.Close(); err != nil {
  190. return err
  191. }
  192. // Close the temporary file
  193. if err := tmpFile.Close(); err != nil {
  194. return err
  195. }
  196. // Replace the original smb.conf file with the temporary file
  197. if err := os.Rename(tmpFile.Name(), "/etc/samba/smb.conf"); err != nil {
  198. return err
  199. }
  200. return nil
  201. }
  202. // ShareExists checks if a given share name exists in smb.conf
  203. func (s *ShareManager) ShareExists(shareName string) (bool, error) {
  204. // Path to smb.conf
  205. smbConfPath := s.SambaConfigPath
  206. // Open the smb.conf file for reading
  207. file, err := os.Open(smbConfPath)
  208. if err != nil {
  209. return false, fmt.Errorf("failed to open smb.conf: %v", err)
  210. }
  211. defer file.Close()
  212. // Check if the share already exists
  213. scanner := bufio.NewScanner(file)
  214. shareNameSection := fmt.Sprintf("[%s]", shareName)
  215. for scanner.Scan() {
  216. if strings.TrimSpace(scanner.Text()) == shareNameSection {
  217. return true, nil
  218. }
  219. }
  220. if err := scanner.Err(); err != nil {
  221. return false, fmt.Errorf("failed to read smb.conf: %v", err)
  222. }
  223. return false, nil
  224. }
  225. // Backup the current smb.conf to the backup folder
  226. func (s *ShareManager) BackupSmbConf() error {
  227. // Define source and backup directory
  228. sourceFile := s.SambaConfigPath
  229. backupDir := s.BackupDir
  230. // Ensure the backup directory exists
  231. err := os.MkdirAll(backupDir, 0755)
  232. if err != nil {
  233. return fmt.Errorf("failed to create backup directory: %v", err)
  234. }
  235. // Create a timestamped backup filename
  236. timestamp := time.Now().Format("20060102_150405")
  237. backupFile := filepath.Join(backupDir, fmt.Sprintf("%s.smb.conf", timestamp))
  238. // Open the source file
  239. src, err := os.Open(sourceFile)
  240. if err != nil {
  241. return fmt.Errorf("failed to open source file: %v", err)
  242. }
  243. defer src.Close()
  244. // Create the destination file
  245. dst, err := os.Create(backupFile)
  246. if err != nil {
  247. return fmt.Errorf("failed to create backup file: %v", err)
  248. }
  249. defer dst.Close()
  250. // Copy the contents of the source file to the backup file
  251. _, err = io.Copy(dst, src)
  252. if err != nil {
  253. return fmt.Errorf("failed to copy file contents: %v", err)
  254. }
  255. return nil
  256. }