setupwizard.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. package main
  2. /*
  3. Setup Wizard backend
  4. The administrator group of a new installation boots into the Setup Wizard
  5. WebApp (web/Setup Wizard, see its README.md) instead of the desktop. Most
  6. of its steps call the endpoints the System Settings pages use (storage
  7. pools, permission groups, accounts, file servers); this file adds what
  8. the wizard needs on top of them:
  9. /system/setup/state everything the wizard shows, in one read
  10. /system/setup/progress the step and choices, so a closed tab resumes
  11. /system/setup/disks the disks of the host and what uses them
  12. /system/setup/disk/format format a disk nothing uses (Linux, password)
  13. /system/setup/disk/add mount a disk partition and add it as a drive
  14. /system/setup/finish boot the admins into their chosen interface
  15. and disable the wizard (also used to skip it)
  16. All of them are admin only.
  17. */
  18. import (
  19. "encoding/json"
  20. "errors"
  21. "net/http"
  22. "os"
  23. "path/filepath"
  24. "runtime"
  25. "sort"
  26. "strings"
  27. fs "imuslab.com/arozos/mod/filesystem"
  28. "imuslab.com/arozos/mod/filesystem/arozfs"
  29. "imuslab.com/arozos/mod/permission"
  30. prout "imuslab.com/arozos/mod/prouter"
  31. "imuslab.com/arozos/mod/setupwizard"
  32. "imuslab.com/arozos/mod/utils"
  33. )
  34. const (
  35. setupWizardTable = "setupwizard"
  36. setupProgressKey = "progress"
  37. setupProgressLimit = 32 << 10 //The saved progress is a small JSON object
  38. interfaceModGroup = "Interface Module"
  39. )
  40. func SetupWizardInit() {
  41. if err := sysdb.NewTable(setupWizardTable); err != nil {
  42. systemWideLogger.PrintAndLog("Setup Wizard", "Could not create the setup wizard table", err)
  43. return
  44. }
  45. router := prout.NewModuleRouter(prout.RouterOption{
  46. ModuleName: "System Setting",
  47. AdminOnly: true,
  48. UserHandler: userHandler,
  49. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  50. utils.SendErrorResponse(w, "Permission Denied")
  51. },
  52. })
  53. router.HandleFunc("/system/setup/state", handleSetupState)
  54. router.HandleFunc("/system/setup/progress", handleSetupProgress)
  55. router.HandleFunc("/system/setup/disks", handleSetupDisks)
  56. router.HandleFunc("/system/setup/disk/format", handleSetupDiskFormat)
  57. router.HandleFunc("/system/setup/disk/add", handleSetupDiskAdd)
  58. router.HandleFunc("/system/setup/finish", handleSetupFinish)
  59. }
  60. /*
  61. State
  62. */
  63. type setupInterfaceInfo struct {
  64. Name string `json:"name"`
  65. Desc string `json:"desc"`
  66. IconPath string `json:"icon"`
  67. }
  68. type setupGroupInfo struct {
  69. Name string `json:"name"`
  70. IsAdmin bool `json:"isAdmin"`
  71. Interface string `json:"interface"`
  72. Quota int64 `json:"quota"`
  73. Modules []string `json:"modules"`
  74. }
  75. type setupFileServerInfo struct {
  76. ID string `json:"id"`
  77. Name string `json:"name"`
  78. Desc string `json:"desc"`
  79. IconPath string `json:"icon"`
  80. Enabled bool `json:"enabled"`
  81. ConfigPage string `json:"configPage"`
  82. }
  83. type setupStateInfo struct {
  84. Active bool `json:"active"` //An admin group still boots into the wizard
  85. Username string `json:"username"`
  86. Hostname string `json:"hostname"`
  87. Platform string `json:"platform"`
  88. CanListDisks bool `json:"canListDisks"`
  89. CanMountDisks bool `json:"canMountDisks"`
  90. DiskNote string `json:"diskNote,omitempty"` //Why disks cannot be mounted: platform, sudo or hardware
  91. Interfaces []setupInterfaceInfo `json:"interfaces"`
  92. AdminInterface string `json:"adminInterface"`
  93. Groups []setupGroupInfo `json:"groups"`
  94. Users []string `json:"users"`
  95. FileServers []setupFileServerInfo `json:"fileServers"`
  96. Progress json.RawMessage `json:"progress"`
  97. }
  98. // setupWizardActive reports whether any group still boots into the wizard
  99. func setupWizardActive() bool {
  100. return len(groupsBootingInto(permission.SetupWizardModule)) > 0
  101. }
  102. // setupInterfaces lists the interface modules a user can boot into, the
  103. // desktop first and the wizard itself left out
  104. func setupInterfaces() []setupInterfaceInfo {
  105. result := []setupInterfaceInfo{}
  106. for _, mod := range moduleHandler.LoadedModule {
  107. if !strings.EqualFold(mod.Group, interfaceModGroup) || mod.Name == permission.SetupWizardModule {
  108. continue
  109. }
  110. result = append(result, setupInterfaceInfo{Name: mod.Name, Desc: mod.Desc, IconPath: mod.IconPath})
  111. }
  112. sort.SliceStable(result, func(i, j int) bool {
  113. return result[i].Name == "Desktop" && result[j].Name != "Desktop"
  114. })
  115. return result
  116. }
  117. func handleSetupState(w http.ResponseWriter, r *http.Request) {
  118. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  119. if err != nil {
  120. utils.SendErrorResponse(w, "User not logged in")
  121. return
  122. }
  123. state := setupStateInfo{
  124. Active: setupWizardActive(),
  125. Username: userinfo.Username,
  126. Hostname: *host_name,
  127. Platform: platformName(),
  128. CanListDisks: setupwizard.Supported,
  129. Interfaces: setupInterfaces(),
  130. Groups: []setupGroupInfo{},
  131. Users: authAgent.ListUsers(),
  132. FileServers: []setupFileServerInfo{},
  133. Progress: json.RawMessage("null"),
  134. }
  135. state.CanMountDisks, state.DiskNote = setupDiskSupport()
  136. for _, pg := range permissionHandler.PermissionGroups {
  137. if pg.Name == "administrator" && pg.DefaultInterfaceModule != permission.SetupWizardModule {
  138. state.AdminInterface = pg.DefaultInterfaceModule
  139. }
  140. state.Groups = append(state.Groups, setupGroupInfo{
  141. Name: pg.Name,
  142. IsAdmin: pg.IsAdmin,
  143. Interface: pg.DefaultInterfaceModule,
  144. Quota: pg.DefaultStorageQuota,
  145. Modules: pg.AccessibleModules,
  146. })
  147. }
  148. sort.Strings(state.Users)
  149. for _, server := range networkFileServerDaemon {
  150. state.FileServers = append(state.FileServers, setupFileServerInfo{
  151. ID: server.ID,
  152. Name: server.Name,
  153. Desc: server.Desc,
  154. IconPath: server.IconPath,
  155. Enabled: server.EnableCheck != nil && server.EnableCheck(),
  156. ConfigPage: server.ConfigPage,
  157. })
  158. }
  159. progress := ""
  160. if err := sysdb.Read(setupWizardTable, setupProgressKey, &progress); err == nil && json.Valid([]byte(progress)) {
  161. state.Progress = json.RawMessage(progress)
  162. }
  163. js, _ := json.Marshal(state)
  164. utils.SendJSONResponse(w, string(js))
  165. }
  166. // platformName is the host OS as the wizard words it
  167. func platformName() string {
  168. if setupwizard.Supported {
  169. return "linux"
  170. }
  171. return runtime.GOOS
  172. }
  173. // setupDiskSupport tells whether disks can be mounted and formatted here,
  174. // and if not, why
  175. func setupDiskSupport() (bool, string) {
  176. switch {
  177. case !setupwizard.Supported:
  178. return false, "platform"
  179. case !*allow_hardware_management:
  180. return false, "hardware"
  181. case !sudo_mode:
  182. return false, "sudo"
  183. }
  184. return true, ""
  185. }
  186. /*
  187. Progress
  188. */
  189. // handleSetupProgress saves (POST progress=<json>) or clears (POST clear=true)
  190. // what the wizard needs to resume. It never holds passwords.
  191. func handleSetupProgress(w http.ResponseWriter, r *http.Request) {
  192. if r.Method != http.MethodPost {
  193. utils.SendErrorResponse(w, "This request must be a POST")
  194. return
  195. }
  196. if clear, _ := utils.PostBool(r, "clear"); clear {
  197. sysdb.Delete(setupWizardTable, setupProgressKey)
  198. utils.SendOK(w)
  199. return
  200. }
  201. progress, err := utils.PostPara(r, "progress")
  202. if err != nil {
  203. utils.SendErrorResponse(w, "progress not defined")
  204. return
  205. }
  206. if len(progress) > setupProgressLimit || !json.Valid([]byte(progress)) {
  207. utils.SendErrorResponse(w, "Invalid progress")
  208. return
  209. }
  210. if err := sysdb.Write(setupWizardTable, setupProgressKey, progress); err != nil {
  211. utils.SendErrorResponse(w, err.Error())
  212. return
  213. }
  214. utils.SendOK(w)
  215. }
  216. /*
  217. Disks
  218. */
  219. // setupUsedDrives lists the local drives of every pool, plus the folder
  220. // ArozOS runs from, so the disks behind them are never offered for format
  221. func setupUsedDrives() []setupwizard.UsedDrive {
  222. used := []setupwizard.UsedDrive{}
  223. absolute := func(path string) string {
  224. if path == "" {
  225. return ""
  226. }
  227. if abs, err := filepath.Abs(path); err == nil {
  228. return filepath.ToSlash(abs)
  229. }
  230. return path
  231. }
  232. for _, pool := range collectPoolStates() {
  233. for _, option := range pool.config {
  234. if arozfs.IsNetworkDrive(option.Filesystem) {
  235. continue
  236. }
  237. used = append(used, setupwizard.UsedDrive{
  238. ID: option.Uuid,
  239. Mountdev: option.Mountdev,
  240. DiskUUID: option.DiskUUID,
  241. Path: absolute(option.Path),
  242. })
  243. }
  244. for _, fsh := range pool.live {
  245. if fsh.IsNetworkDrive() || fsh.Path == "" {
  246. continue
  247. }
  248. used = append(used, setupwizard.UsedDrive{ID: fsh.UUID, Path: absolute(fsh.Path)})
  249. }
  250. }
  251. if wd, err := os.Getwd(); err == nil {
  252. used = append(used, setupwizard.UsedDrive{ID: "arozos", Path: absolute(wd)})
  253. }
  254. return used
  255. }
  256. func handleSetupDisks(w http.ResponseWriter, r *http.Request) {
  257. disks, err := setupwizard.ListDisks(setupUsedDrives())
  258. if err != nil {
  259. utils.SendErrorResponse(w, err.Error())
  260. return
  261. }
  262. js, _ := json.Marshal(disks)
  263. utils.SendJSONResponse(w, string(js))
  264. }
  265. // setupConfirmPassword checks the signed in admin's password, which every
  266. // destructive disk action asks for again
  267. func setupConfirmPassword(w http.ResponseWriter, r *http.Request) bool {
  268. username, err := authAgent.GetUserName(w, r)
  269. if err != nil {
  270. utils.SendErrorResponse(w, "User not logged in")
  271. return false
  272. }
  273. password, err := utils.PostPara(r, "password")
  274. if err != nil || password == "" {
  275. utils.SendErrorResponse(w, "Enter your password to continue")
  276. return false
  277. }
  278. if ok, reason := authAgent.ValidateUsernameAndPasswordWithReason(username, password); !ok {
  279. utils.SendErrorResponse(w, reason)
  280. return false
  281. }
  282. return true
  283. }
  284. // handleSetupDiskFormat formats a partition, or a disk without partitions,
  285. // that nothing uses. POST device, fstype, label, password
  286. func handleSetupDiskFormat(w http.ResponseWriter, r *http.Request) {
  287. if r.Method != http.MethodPost {
  288. utils.SendErrorResponse(w, "This request must be a POST")
  289. return
  290. }
  291. if canMount, note := setupDiskSupport(); !canMount {
  292. utils.SendErrorResponse(w, "Disks cannot be formatted on this server ("+note+")")
  293. return
  294. }
  295. device, err := utils.PostPara(r, "device")
  296. if err != nil {
  297. utils.SendErrorResponse(w, "device not defined")
  298. return
  299. }
  300. fstype, err := utils.PostPara(r, "fstype")
  301. if err != nil || !utils.StringInArray(setupwizard.FormatTypes, fstype) {
  302. utils.SendErrorResponse(w, "File system not supported")
  303. return
  304. }
  305. label, _ := utils.PostPara(r, "label")
  306. if !setupConfirmPassword(w, r) {
  307. return
  308. }
  309. username, _ := authAgent.GetUserName(w, r)
  310. systemWideLogger.PrintAndLog("Setup Wizard", username+" is formatting "+device+" as "+fstype, nil)
  311. if err := setupwizard.Format(device, fstype, label, setupUsedDrives()); err != nil {
  312. systemWideLogger.PrintAndLog("Setup Wizard", "Formatting "+device+" failed", err)
  313. utils.SendErrorResponse(w, err.Error())
  314. return
  315. }
  316. systemWideLogger.PrintAndLog("Setup Wizard", device+" formatted as "+fstype, nil)
  317. utils.SendOK(w)
  318. }
  319. // handleSetupDiskAdd adds a disk partition to the system pool as a drive.
  320. // A partition nothing mounts is mounted under the media folder at every
  321. // start; one the host already mounts is used as a plain folder.
  322. // POST device, id, name, hierarchy (public or user)
  323. func handleSetupDiskAdd(w http.ResponseWriter, r *http.Request) {
  324. if r.Method != http.MethodPost {
  325. utils.SendErrorResponse(w, "This request must be a POST")
  326. return
  327. }
  328. device, err := utils.PostPara(r, "device")
  329. if err != nil {
  330. utils.SendErrorResponse(w, "device not defined")
  331. return
  332. }
  333. id, _ := utils.PostPara(r, "id")
  334. id = strings.TrimSpace(id)
  335. if !setupwizard.ValidDriveID(id) {
  336. utils.SendErrorResponse(w, "A drive id can only contain letters, numbers, - and _")
  337. return
  338. }
  339. name, _ := utils.PostPara(r, "name")
  340. name = strings.TrimSpace(name)
  341. if name == "" {
  342. name = id
  343. }
  344. hierarchy, _ := utils.PostPara(r, "hierarchy")
  345. if hierarchy != "user" {
  346. hierarchy = "public"
  347. }
  348. disks, err := setupwizard.ListDisks(setupUsedDrives())
  349. if err != nil {
  350. utils.SendErrorResponse(w, err.Error())
  351. return
  352. }
  353. _, part, err := setupwizard.FindPartition(disks, device)
  354. if err != nil {
  355. utils.SendErrorResponse(w, err.Error())
  356. return
  357. }
  358. if !part.CanAdd {
  359. utils.SendErrorResponse(w, "This disk cannot be added as a drive")
  360. return
  361. }
  362. option := fs.FileSystemOption{
  363. Name: name,
  364. Uuid: id,
  365. Access: arozfs.FsReadWrite,
  366. Hierarchy: hierarchy,
  367. Filesystem: part.Fstype,
  368. }
  369. mountpoint := ""
  370. if part.AddMode == setupwizard.AddMount {
  371. if canMount, note := setupDiskSupport(); !canMount {
  372. utils.SendErrorResponse(w, "Disks cannot be mounted on this server ("+note+")")
  373. return
  374. }
  375. //Refuse a taken id before a folder is made for it
  376. if err := validateNewDrive(&fs.FileSystemOption{Name: name, Uuid: id, Path: ".", Access: arozfs.FsReadWrite, Hierarchy: hierarchy, Filesystem: part.Fstype}, collectPoolStates()); err != nil {
  377. utils.SendErrorResponse(w, err.Error())
  378. return
  379. }
  380. mountpoint, err = setupwizard.PrepareMountPoint(id)
  381. if err != nil {
  382. utils.SendErrorResponse(w, err.Error())
  383. return
  384. }
  385. option.Path = mountpoint
  386. option.Automount = true
  387. option.Mountdev = part.Path
  388. option.Mountpt = mountpoint
  389. option.DiskUUID = part.UUID
  390. } else {
  391. option.Path = part.Mountpoint
  392. }
  393. mountErr, err := addDrive(storagePoolSystem, option, nil)
  394. if err == nil && mountErr == nil && mountpoint != "" && !fs.CheckMounted(mountpoint) {
  395. //mount failed quietly: never let the drive write into the empty folder
  396. mountErr = errors.New("The disk could not be mounted on " + mountpoint)
  397. }
  398. if err != nil || mountErr != nil {
  399. if err == nil {
  400. //Saved but not usable: take it out again, so the user can retry
  401. removeDrive(storagePoolSystem, id)
  402. err = mountErr
  403. }
  404. if mountpoint != "" {
  405. //Only removes the folder if it is still empty
  406. os.Remove(mountpoint)
  407. }
  408. systemWideLogger.PrintAndLog("Setup Wizard", "Adding "+device+" as "+id+":/ failed", err)
  409. utils.SendErrorResponse(w, err.Error())
  410. return
  411. }
  412. systemWideLogger.PrintAndLog("Setup Wizard", device+" added as drive "+id+":/", nil)
  413. js, _ := json.Marshal(map[string]string{"uuid": id, "path": option.Path})
  414. utils.SendJSONResponse(w, string(js))
  415. }
  416. /*
  417. Finish
  418. */
  419. // handleSetupFinish boots every group that still opens the wizard into the
  420. // chosen interface, then disables the wizard. Skipping uses it too, with the
  421. // desktop. POST interface=<module name>
  422. func handleSetupFinish(w http.ResponseWriter, r *http.Request) {
  423. if r.Method != http.MethodPost {
  424. utils.SendErrorResponse(w, "This request must be a POST")
  425. return
  426. }
  427. target, err := utils.PostPara(r, "interface")
  428. if err != nil {
  429. target = "Desktop"
  430. }
  431. if err := finishSetupWizard(target); err != nil {
  432. utils.SendErrorResponse(w, err.Error())
  433. return
  434. }
  435. username, _ := authAgent.GetUserName(w, r)
  436. systemWideLogger.PrintAndLog("Setup Wizard", "Setup finished by "+username+", interface: "+target, nil)
  437. utils.SendOK(w)
  438. }
  439. func finishSetupWizard(target string) error {
  440. valid := false
  441. for _, iface := range setupInterfaces() {
  442. if iface.Name == target {
  443. valid = true
  444. }
  445. }
  446. if !valid {
  447. return errors.New("Not an interface module: " + target)
  448. }
  449. //When the wizard was opened again by an admin, their group gets the
  450. //chosen interface even though it no longer boots into the wizard
  451. groups := groupsBootingInto(permission.SetupWizardModule)
  452. if len(groups) == 0 {
  453. groups = []string{"administrator"}
  454. }
  455. for _, group := range groups {
  456. if err := permissionHandler.SetInterfaceModule(group, target); err != nil {
  457. return err
  458. }
  459. }
  460. sysdb.Delete(setupWizardTable, setupProgressKey)
  461. if moduleHandler.GetModuleInfoByID(permission.SetupWizardModule) != nil {
  462. if err := moduleHandler.SetModuleEnabled(permission.SetupWizardModule, false); err != nil {
  463. return err
  464. }
  465. }
  466. return nil
  467. }