Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
347 lines (309 loc) 路 10.8 KB
/
Copy pathmain.go
File metadata and controls
347 lines (309 loc) 路 10.8 KB
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
package main
//go:generate go tool goversioninfo -icon=res/papp.ico -manifest=res/papp.manifest
import (
_ "embed"
"encoding/json"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/portapps/portapps/v3"
"github.com/portapps/portapps/v3/pkg/files"
"github.com/portapps/portapps/v3/pkg/log"
"github.com/portapps/portapps/v3/pkg/mutex"
"github.com/portapps/portapps/v3/pkg/shortcut"
"github.com/portapps/portapps/v3/pkg/win"
"golang.org/x/sys/windows/registry"
)
//go:embed res/FirefoxDeveloperEdition.lnk
var defaultShortcut []byte
type config struct {
Profile string `yaml:"profile" mapstructure:"profile"`
MultipleInstances bool `yaml:"multiple_instances" mapstructure:"multiple_instances"`
DisableTelemetry bool `yaml:"disable_telemetry" mapstructure:"disable_telemetry"`
DisableCrashReporter bool `yaml:"disable_crash_reporter" mapstructure:"disable_crash_reporter"`
Cleanup bool `yaml:"cleanup" mapstructure:"cleanup"`
}
var (
app *portapps.App
cfg *config
)
func init() {
var err error
// Default config
cfg = &config{
Profile: "default",
MultipleInstances: false,
DisableTelemetry: false,
DisableCrashReporter: true,
Cleanup: false,
}
// Init app
if app, err = portapps.NewWithCfg("phyrox-developer-portable", "Phyrox Developer Edition", cfg); err != nil {
log.Fatal().Err(err).Msg("Cannot initialize application. See log file for more info.")
}
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "register-browser" {
if len(os.Args) != 2 {
app.FatalBox(fmt.Errorf("Usage: %s register-browser", filepath.Base(os.Args[0])))
return
}
if err := registerBrowser(); err != nil {
app.FatalBox(err)
return
}
if _, err := win.MsgBox(
"Phyrox Developer Edition Portable",
"Browser registered for the current user. Select Phyrox Developer Edition Portable for HTTP and HTTPS in Windows Settings > Apps > Default apps.",
win.MsgBoxBtnOk|win.MsgBoxIconInformation); err != nil {
log.Error().Err(err).Msg("Cannot display registration confirmation")
}
return
}
args, err := launchArgs(os.Args[1:])
if err != nil {
app.FatalBox(err)
return
}
if len(os.Args) > 1 && os.Args[1] == "--open-url" && cfg.MultipleInstances {
app.FatalBox(fmt.Errorf("Opening external links requires app.multiple_instances: false"))
return
}
profileFolder := filepath.Join(app.DataPath, "profile", cfg.Profile)
for _, dir := range []string{app.DataPath, profileFolder} {
if err := os.MkdirAll(dir, 0o755); err != nil {
log.Fatal().Err(err).Msgf("Cannot create directory %s", dir)
}
}
app.Process = filepath.Join(app.AppPath, "firefox.exe")
app.Args = []string{
"-profile",
profileFolder,
}
// Set env vars
crashreporterFolder := filepath.Join(app.DataPath, "crashreporter")
pluginsFolder := filepath.Join(app.DataPath, "plugins")
for _, dir := range []string{crashreporterFolder, pluginsFolder} {
if err := os.MkdirAll(dir, 0o755); err != nil {
log.Fatal().Err(err).Msgf("Cannot create directory %s", dir)
}
}
os.Setenv("MOZ_CRASHREPORTER_DATA_DIRECTORY", crashreporterFolder)
os.Setenv("MOZ_MAINTENANCE_SERVICE", "0")
os.Setenv("MOZ_PLUGIN_PATH", pluginsFolder)
os.Setenv("MOZ_UPDATER", "0")
if cfg.DisableCrashReporter {
os.Setenv("MOZ_CRASHREPORTER", "0")
os.Setenv("MOZ_CRASHREPORTER_DISABLE", "1")
os.Setenv("MOZ_CRASHREPORTER_NO_REPORT", "1")
}
if cfg.DisableTelemetry {
os.Setenv("MOZ_DATA_REPORTING", "0")
}
// Create and check mutex
mu, err := mutex.Create(app.ID)
if err != nil {
if !cfg.MultipleInstances {
if len(args) > 0 {
log.Info().Msg("Forwarding arguments to the running instance")
app.Launch(args)
return
}
log.Error().Msg("You have to enable multiple instances in your configuration if you want to launch another instance")
if _, err = win.MsgBox(
fmt.Sprintf("%s portable", app.Name),
"Other instance detected. You have to enable multiple instances in your configuration if you want to launch another instance.",
win.MsgBoxBtnOk|win.MsgBoxIconError); err != nil {
log.Error().Err(err).Msg("Cannot create dialog box")
}
return
} else {
log.Warn().Msg("Another instance is already running")
}
} else {
defer mutex.Release(mu)
}
// Cleanup on exit
if cfg.Cleanup {
defer func() {
files.Cleanup(
filepath.Join(os.Getenv("APPDATA"), "Mozilla", "Firefox"),
filepath.Join(os.Getenv("LOCALAPPDATA"), "Mozilla", "Firefox"),
filepath.Join(os.Getenv("USERPROFILE"), "AppData", "LocalLow", "Mozilla"),
)
}()
}
// Multiple instances
if cfg.MultipleInstances {
log.Info().Msg("Multiple instances enabled")
app.Args = append(app.Args, "-no-remote")
}
// Policies
if err := createPolicies(); err != nil {
log.Fatal().Err(err).Msg("Cannot create policies")
}
// Fix extensions path
if err := updateAddonStartup(profileFolder); err != nil {
log.Error().Err(err).Msg("Cannot fix extensions path")
}
// Copy default shortcut
shortcutPath := filepath.Join(os.Getenv("APPDATA"), "Microsoft", "Windows", "Start Menu", "Programs", "Phyrox Developer Edition Portable.lnk")
err = os.WriteFile(shortcutPath, defaultShortcut, 0644)
if err != nil {
log.Error().Err(err).Msg("Cannot write default shortcut")
}
// Update default shortcut
err = shortcut.Create(shortcut.Shortcut{
ShortcutPath: shortcutPath,
TargetPath: app.Process,
Arguments: shortcut.Property{Clear: true},
Description: shortcut.Property{Value: "Phyrox Developer Edition Portable by Portapps"},
IconLocation: shortcut.Property{Value: app.Process},
WorkingDirectory: shortcut.Property{Value: app.AppPath},
})
if err != nil {
log.Error().Err(err).Msg("Cannot create shortcut")
}
defer func() {
if err := os.Remove(shortcutPath); err != nil {
log.Error().Err(err).Msg("Cannot remove shortcut")
}
}()
defer app.Close()
app.Launch(args)
}
// launchArgs keeps Windows URL associations separate from Firefox's CLI. Reject
// extra arguments so an external URL cannot inject Firefox command-line flags.
func launchArgs(args []string) ([]string, error) {
if len(args) == 0 || args[0] != "--open-url" {
return args, nil
}
if len(args) != 2 {
return nil, fmt.Errorf("--open-url requires exactly one HTTP or HTTPS URL")
}
u, err := url.Parse(args[1])
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return nil, fmt.Errorf("--open-url requires an absolute HTTP or HTTPS URL")
}
return []string{"-url", args[1]}, nil
}
// registerBrowser makes this wrapper available in Windows Default apps without
// changing the user's defaults or starting Firefox.
func registerBrowser() error {
wrapper, err := os.Executable()
if err != nil {
return err
}
const progID = `Software\Classes\Portapps.PhyroxDeveloper.Url`
const capabilities = `Software\Portapps\PhyroxDeveloper\Capabilities`
entries := []struct {
path string
name string
value string
}{
{progID, "", "Phyrox Developer Edition Portable URL"},
{progID, "URL Protocol", ""},
{progID + `\DefaultIcon`, "", fmt.Sprintf(`"%s",0`, wrapper)},
{progID + `\shell\open\command`, "", fmt.Sprintf(`"%s" --open-url "%%1"`, wrapper)},
{capabilities, "ApplicationName", "Phyrox Developer Edition Portable"},
{capabilities, "ApplicationDescription", "Firefox via the Portapps portable wrapper"},
{capabilities + `\URLAssociations`, "http", "Portapps.PhyroxDeveloper.Url"},
{capabilities + `\URLAssociations`, "https", "Portapps.PhyroxDeveloper.Url"},
{`Software\RegisteredApplications`, "Phyrox Developer Edition Portable", capabilities},
}
for _, entry := range entries {
key, _, err := registry.CreateKey(registry.CURRENT_USER, entry.path, registry.SET_VALUE)
if err != nil {
return fmt.Errorf("Cannot create registry key %s: %w", entry.path, err)
}
err = key.SetStringValue(entry.name, entry.value)
key.Close()
if err != nil {
return fmt.Errorf("Cannot set registry value %s\\%s: %w", entry.path, entry.name, err)
}
}
return nil
}
func createPolicies() error {
distributionPath := filepath.Join(app.AppPath, "distribution")
if err := os.MkdirAll(distributionPath, 0o755); err != nil {
return errors.Wrap(err, "Cannot create distribution directory")
}
appFile := filepath.Join(distributionPath, "policies.json")
dataFile := filepath.Join(app.DataPath, "policies.json")
jsonPolicies := map[string]interface{}{
"policies": map[string]interface{}{},
}
defaultPolicies, err := json.Marshal(jsonPolicies)
if err != nil {
return errors.Wrap(err, "Cannot marshal default policies")
}
log.Debug().Msgf("Default policies: %s", string(defaultPolicies))
if files.Exists(dataFile) {
rawCustomPolicies, err := os.ReadFile(dataFile)
if err != nil {
return errors.Wrap(err, "Cannot read custom policies")
}
if err := json.Unmarshal(rawCustomPolicies, &jsonPolicies); err != nil {
return errors.Wrap(err, "Cannot consume custom policies")
}
customPolicies, err := json.Marshal(jsonPolicies)
if err != nil {
return errors.Wrap(err, "Cannot marshal custom policies")
}
log.Debug().Msgf("Custom policies: %s", string(customPolicies))
}
policies, ok := jsonPolicies["policies"].(map[string]interface{})
if !ok {
if _, exists := jsonPolicies["policies"]; exists {
return errors.New("policies must be an object")
}
policies = map[string]interface{}{}
jsonPolicies["policies"] = policies
}
policies["DisableAppUpdate"] = true
policies["DontCheckDefaultBrowser"] = true
if cfg.DisableTelemetry {
policies["DisableFirefoxStudies"] = true
policies["DisableTelemetry"] = true
}
appliedPolicies, err := json.MarshalIndent(jsonPolicies, "", " ")
if err != nil {
return errors.Wrap(err, "Cannot marshal policies")
}
log.Debug().Msgf("Applied policies: %s", string(appliedPolicies))
if err := os.WriteFile(appFile, appliedPolicies, 0644); err != nil {
return errors.Wrap(err, "Cannot write policies")
}
return nil
}
func updateAddonStartup(profileFolder string) error {
lz4File := filepath.Join(profileFolder, "addonStartup.json.lz4")
if !files.Exists(lz4File) || app.Prev.RootPath == "" {
return nil
}
lz4Raw, err := mozLz4Decompress(lz4File)
if err != nil {
return err
}
prevPathLin := escapedUnixPath(app.Prev.RootPath)
currPathLin := escapedUnixPath(app.RootPath)
lz4Str := strings.ReplaceAll(string(lz4Raw), prevPathLin, currPathLin)
prevPathWin := escapedWindowsPath(app.Prev.RootPath)
currPathWin := escapedWindowsPath(app.RootPath)
lz4Str = strings.ReplaceAll(lz4Str, prevPathWin, currPathWin)
lz4Enc, err := mozLz4Compress([]byte(lz4Str))
if err != nil {
return err
}
return os.WriteFile(lz4File, lz4Enc, 0644)
}
func escapedUnixPath(path string) string {
return strings.ReplaceAll(filepath.ToSlash(path), ` `, `%20`)
}
func escapedWindowsPath(path string) string {
return strings.ReplaceAll(strings.ReplaceAll(filepath.FromSlash(path), `\`, `\\`), ` `, `%20`)
}