helpers.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package samba
  2. import (
  3. "fmt"
  4. "os/exec"
  5. "path/filepath"
  6. "strings"
  7. )
  8. // convertShareConfigToString converts a ShareConfig to its string representation for smb.conf
  9. func convertShareConfigToString(share *ShareConfig) string {
  10. var builder strings.Builder
  11. builder.WriteString(fmt.Sprintf("\n[%s]\n", share.Name))
  12. builder.WriteString(fmt.Sprintf("\tpath = %s\n", share.Path))
  13. if len(share.ValidUsers) > 0 {
  14. builder.WriteString(fmt.Sprintf("\tvalid users = %s\n", strings.Join(share.ValidUsers, " ")))
  15. }
  16. builder.WriteString(fmt.Sprintf("\tread only = %s\n", boolToYesNo(share.ReadOnly)))
  17. builder.WriteString(fmt.Sprintf("\tbrowseable = %s\n", boolToYesNo(share.Browseable)))
  18. builder.WriteString(fmt.Sprintf("\tguest ok = %s\n", boolToYesNo(share.GuestOk)))
  19. return builder.String()
  20. }
  21. // boolToYesNo converts a boolean to "yes" or "no"
  22. func boolToYesNo(value bool) string {
  23. if value {
  24. return "yes"
  25. }
  26. return "no"
  27. }
  28. // RestartSmbd restarts the smbd service using systemctl
  29. func restartSmbd() error {
  30. cmd := exec.Command("sudo", "systemctl", "restart", "smbd")
  31. output, err := cmd.CombinedOutput()
  32. if err != nil {
  33. return fmt.Errorf("failed to restart smbd: %v - %s", err, output)
  34. }
  35. return nil
  36. }
  37. // Check if a samba username exists (unix username only)
  38. func (s *ShareManager) SambaUserExists(username string) (bool, error) {
  39. userInfos, err := s.ListSambaUsersInfo()
  40. if err != nil {
  41. return false, err
  42. }
  43. for _, userInfo := range userInfos {
  44. if userInfo.UnixUsername == username {
  45. return true, nil
  46. }
  47. }
  48. return false, nil
  49. }
  50. // List of important folders not to be shared via SMB
  51. var importantFolders = []string{
  52. "/bin",
  53. "/boot",
  54. "/dev",
  55. "/etc",
  56. "/lib",
  57. "/lib64",
  58. "/proc",
  59. "/root",
  60. "/sbin",
  61. "/sys",
  62. "/tmp",
  63. "/usr",
  64. "/var",
  65. }
  66. // IsPathInsideImportantFolders checks if the given path is inside one of the important folders
  67. func isPathInsideImportantFolders(path string) bool {
  68. // Clean the given path
  69. cleanedPath := filepath.Clean(path)
  70. // Iterate over the important folders
  71. for _, folder := range importantFolders {
  72. // Clean the important folder path
  73. cleanedFolder := filepath.Clean(folder)
  74. // Check if the cleaned path is inside the cleaned folder
  75. if strings.HasPrefix(cleanedPath, cleanedFolder) {
  76. return true
  77. }
  78. }
  79. return false
  80. }