setupwizard.go 16 KB

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