1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package main

import (
	"database/sql"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// =============================================================================
// hosty start / stop / run — shared setup logic
// =============================================================================

type setupConfig struct {
	hostyFile          string // optional path to .hosty file
	name               string // optional override; required if hostyFile empty
	port               string
	stateDir           string
	ignoreVersionCheck bool
	system             bool // system mode: attach as a root portable service instead of a --user unit
}

// resolvedSetup is the result of the shared setup logic.
type resolvedSetup struct {
	name     string
	port     string
	dataPath string // <stateDir>/<name>/data.hosty
	rootfs   string // <stateDir>/<name>/rootfs (user mode) or image tree (system mode)
	fsDir    string // <stateDir>/<name>/fs  — FUSE mount point
	credsDir string // <stateDir>/<name>/credentials — ephemeral credential files
	system   bool   // system mode: attached as a root portable service
}

func defaultStateDir() string {
	if s := os.Getenv("XDG_STATE_HOME"); s != "" {
		return filepath.Join(s, "hosty")
	}
	return filepath.Join(os.Getenv("HOME"), ".local", "state", "hosty")
}

// systemStateDir is the state root for system mode (root portable services).
const systemStateDir = "/var/lib/hosty"

// systemRuntimeSubdir is the RuntimeDirectory= value (relative to /run) used by
// the system-mode FUSE unit, and systemFSDir is the resulting mount point.
func systemRuntimeSubdir(name string) string { return "hosty/" + name }
func systemFSDir(name string) string         { return filepath.Join("/run", systemRuntimeSubdir(name), "fs") }

// defaultStateDirFor returns the appropriate default state dir for the mode.
func defaultStateDirFor(system bool) string {
	if system {
		return systemStateDir
	}
	return defaultStateDir()
}

// resolveStateDir turns the -state-dir flag into the directory to use, applying
// the mode's default when unset.
//
// A relative path is rejected rather than silently made absolute. Every path
// hosty derives from the state dir is written verbatim into a systemd unit
// (ExecStart=, WorkingDirectory=, Environment=HOSTY_DB=...), and systemd
// requires those to be absolute: it refuses the whole unit with "path is not
// absolute" at load time. Resolving against the current directory instead would
// be worse than failing, because the unit outlives the shell that created it and
// would silently point somewhere else on the next boot.
func resolveStateDir(flagVal string, system bool) (string, error) {
	if flagVal == "" {
		return defaultStateDirFor(system), nil
	}
	if !filepath.IsAbs(flagVal) {
		abs, err := filepath.Abs(flagVal)
		if err != nil {
			return "", fmt.Errorf("-state-dir %q must be an absolute path", flagVal)
		}
		return "", fmt.Errorf("-state-dir %q must be an absolute path (did you mean %s?)", flagVal, abs)
	}
	return filepath.Clean(flagVal), nil
}

// setup implements the shared start/run setup logic:
// resolves name, copies/upgrades data.hosty, extracts rootfs, writes unit file.
func setup(cfg setupConfig) (*resolvedSetup, error) {
	// Callers normally resolve this already; repeated here so that setup() is
	// safe on its own and 'hosty run' gets the same validation as 'hosty start'.
	stateDir, err := resolveStateDir(cfg.stateDir, cfg.system)
	if err != nil {
		return nil, err
	}

	// Determine name: from file if not overridden
	name := cfg.name
	var fileDB *sql.DB
	if cfg.hostyFile != "" {
		fileDB, err = openImageFileDB(cfg.hostyFile)
		if err != nil {
			return nil, fmt.Errorf("opening %s: %w", cfg.hostyFile, err)
		}
		defer fileDB.Close()

		if name == "" {
			name, err = metaGet(fileDB, "name")
			if err != nil {
				return nil, fmt.Errorf("reading name from %s: %w", cfg.hostyFile, err)
			}
		}
	}
	if name == "" {
		return nil, fmt.Errorf("-name required when no .hosty file is given")
	}
	// Validate before deriving any path from the name, so that a bad name is
	// rejected without creating state. This covers -name overriding the packed
	// name as well as the packed name itself (an image packed by an older hosty
	// may carry a name that predates this check).
	if err := validateAppName(name); err != nil {
		return nil, err
	}

	appDir := filepath.Join(stateDir, name)
	dataPath := filepath.Join(appDir, "data.hosty")

	// FUSE mount point. In system mode it must NOT live under the app's
	// StateDirectory: with DynamicUser the state dir is relocated to
	// /var/lib/private/... and replaced by a symlink, so the mounting fs unit
	// (which has no StateDirectory) and the app would disagree on the path —
	// unmount then fails. /run is never relocated, so both agree there. The dir
	// is provisioned by RuntimeDirectory= on the fs unit.
	fsDir := filepath.Join(appDir, "fs")
	if cfg.system {
		fsDir = systemFSDir(name)
	}

	// In system mode the extracted image tree doubles as the portable-service
	// image; portabled registers it under its directory basename, so it must be
	// unique per app. Place it at <stateDir>/images/<name> so the image name is
	// exactly <name> (matching the packed unit prefix). In user mode the tree is
	// just the ExecStart rootfs and lives under the app dir.
	var rootfs string
	if cfg.system {
		rootfs = filepath.Join(stateDir, "images", name)
	} else {
		rootfs = filepath.Join(appDir, "rootfs")
	}

	if err := os.MkdirAll(appDir, 0755); err != nil {
		return nil, fmt.Errorf("creating state dir: %w", err)
	}

	dataExists := fileExists(dataPath)
	needExtract := false

	if dataExists {
		dataDB, err := openDB(dataPath)
		if err != nil {
			return nil, fmt.Errorf("opening data.hosty: %w", err)
		}
		defer dataDB.Close()

		if fileDB != nil {
			// Compare checksums
			existingSHA, err := metaGet(dataDB, "image_sha256")
			if err != nil {
				return nil, err
			}
			newSHA, err := metaGet(fileDB, "image_sha256")
			if err != nil {
				return nil, err
			}

			if existingSHA != newSHA {
				// Read version strings for comparison and logging.
				existingVersion, _ := metaGet(dataDB, "version")
				newVersion, _ := metaGet(fileDB, "version")

				switch {
				case newVersion < existingVersion:
					if !cfg.ignoreVersionCheck {
						return nil, fmt.Errorf(
							"refusing upgrade: new version %q is not greater than installed %q (use -ignore-version-check to override)",
							newVersion, existingVersion,
						)
					}
					fmt.Fprintf(os.Stderr, "hosty: warning: downgrading %s %s → %s (sha256 %s → %s, -ignore-version-check set)\n",
						name, existingVersion, newVersion, existingSHA[:12], newSHA[:12])
				case newVersion == existingVersion:
					fmt.Fprintf(os.Stderr, "hosty: warning: same version %q but different image (sha256 %s → %s)\n",
						existingVersion, existingSHA[:12], newSHA[:12])
				default:
					fmt.Fprintf(os.Stderr, "hosty: upgrading %s %s → %s (sha256 %s → %s)\n",
						name, existingVersion, newVersion, existingSHA[:12], newSHA[:12])
				}

				if err := upgradeImage(dataDB, fileDB); err != nil {
					return nil, fmt.Errorf("upgrading image: %w", err)
				}
				needExtract = true
			} else {
				existingVersion, _ := metaGet(dataDB, "version")
				needExtract = !dirExists(rootfs)
				if needExtract {
					fmt.Fprintf(os.Stderr, "hosty: image unchanged (version %s, sha256 %s) — re-extracting rootfs\n", existingVersion, existingSHA[:12])
				} else {
					fmt.Fprintf(os.Stderr, "hosty: image unchanged (version %s, sha256 %s)\n", existingVersion, existingSHA[:12])
				}
			}
		} else {
			// No file given — resume from existing data
			needExtract = !dirExists(rootfs)
		}
	} else {
		// Fresh install — file required
		if fileDB == nil {
			return nil, fmt.Errorf("no existing data for %q and no .hosty file given", name)
		}
		fmt.Fprintf(os.Stderr, "hosty: installing %s fresh\n", name)
		if err := copyFile(cfg.hostyFile, dataPath); err != nil {
			return nil, fmt.Errorf("copying data.hosty: %w", err)
		}
		needExtract = true
	}

	if needExtract {
		// Extract image blob from data.hosty → image.raw → rootfs/
		dataDB, err := openDB(dataPath)
		if err != nil {
			return nil, fmt.Errorf("opening data.hosty: %w", err)
		}
		defer dataDB.Close()

		fmt.Fprintf(os.Stderr, "hosty: extracting image\n")
		os.RemoveAll(rootfs)
		if err := os.MkdirAll(rootfs, 0755); err != nil {
			return nil, fmt.Errorf("creating rootfs dir: %w", err)
		}
		if err := extractImageFS(dataDB, rootfs); err != nil {
			return nil, fmt.Errorf("extracting image: %w", err)
		}
	}

	// Open data.hosty for reading config + writing any needed migrations.
	unitDB, err := openDB(dataPath)
	if err != nil {
		return nil, fmt.Errorf("opening data.hosty: %w", err)
	}
	defer unitDB.Close()

	// Ensure _hosty_config has the value column (added after initial deploy).
	_, _ = unitDB.Exec(`ALTER TABLE _hosty_config ADD COLUMN value TEXT`)

	// Open (or create) the environment database — holds the port assignment and
	// sensitive config values for every app in this state dir.
	envDB, err := openEnvDB(stateDir)
	if err != nil {
		return nil, err
	}
	defer envDB.Close()

	// Register before writing anything app-scoped: secrets carry an enforced
	// foreign key to this row.
	if err := appRegister(envDB, name); err != nil {
		return nil, err
	}

	// Strip sensitive values that arrived in an imported .hosty file: write them
	// to the environment database first, then NULL them in data.hosty.
	if err := stripSensitiveFromData(unitDB, envDB, name); err != nil {
		return nil, fmt.Errorf("stripping sensitive config from data.hosty: %w", err)
	}

	// Check required config.
	hard, soft, err := missingRequiredConfig(unitDB, envDB, name)
	if err != nil {
		return nil, fmt.Errorf("checking required config: %w", err)
	}
	if len(hard) > 0 {
		var b strings.Builder
		fmt.Fprintf(&b, "missing required config for %s:\n", name)
		for _, e := range hard {
			fmt.Fprintf(&b, "\n  %-20s %s", e.key, e.desc)
		}
		fmt.Fprintf(&b, "\n\nSet them with:")
		for _, e := range hard {
			fmt.Fprintf(&b, "\n  hosty config%s -name %s -set %s=...", systemFlagArg(cfg.system), name, e.key)
		}
		return nil, fmt.Errorf("%s", b.String())
	}
	for _, e := range soft {
		fmt.Fprintf(os.Stderr, "hosty: warning: sensitive required config %q is not set — service may fail to start\n", e.key)
		fmt.Fprintf(os.Stderr, "hosty: warning:   set it with: hosty config%s -name %s -set %s=...\n", systemFlagArg(cfg.system), name, e.key)
		fmt.Fprintf(os.Stderr, "hosty: warning:   or inject it externally via a systemd drop-in\n")
	}

	// Resolve port: explicit flag > stored port > new free port.
	if cfg.port == "" {
		existing, err := appPort(envDB, name)
		if err != nil {
			return nil, err
		}
		if existing != "" {
			cfg.port = existing
		} else {
			p, err := freePort()
			if err != nil {
				return nil, err
			}
			cfg.port = p
			fmt.Fprintf(os.Stderr, "hosty: assigned port %s\n", cfg.port)
		}
	}
	if err := appSetPort(envDB, name, cfg.port); err != nil {
		return nil, err
	}
	// Write sensitive config values to per-key credential files.
	credsDir, err := writeCredentials(appDir, unitDB, envDB, name)
	if err != nil {
		return nil, fmt.Errorf("writing credentials: %w", err)
	}

	// Create the FUSE mount point directory (must exist before the fs unit
	// mounts it, and before the app service bind-mounts it in system mode).
	if err := os.MkdirAll(fsDir, 0755); err != nil {
		return nil, fmt.Errorf("creating fs dir: %w", err)
	}

	if cfg.system {
		if err := setupSystemUnits(name, cfg.port, rootfs, dataPath, fsDir, credsDir, stateDir, unitDB, envDB); err != nil {
			return nil, err
		}
	} else {
		if err := writeUnitFile(name, cfg.port, rootfs, dataPath, fsDir, credsDir, unitDB); err != nil {
			return nil, fmt.Errorf("writing unit file: %w", err)
		}
		if err := writeFSUnitFile(name, stateDir); err != nil {
			return nil, fmt.Errorf("writing fs unit file: %w", err)
		}
		if err := runCmd("systemctl", "--user", "daemon-reload"); err != nil {
			return nil, fmt.Errorf("daemon-reload: %w", err)
		}
	}

	return &resolvedSetup{
		name:     name,
		port:     cfg.port,
		dataPath: dataPath,
		rootfs:   rootfs,
		fsDir:    fsDir,
		credsDir: credsDir,
		system:   cfg.system,
	}, nil
}