-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathnative.go
401 lines (329 loc) Β· 9.31 KB
/
native.go
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package native
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"github.com/itchio/httpkit/neterr"
"github.com/itchio/pelican"
"github.com/itchio/dash"
"github.com/itchio/butler/butlerd/messages"
"github.com/itchio/butler/filtering"
"github.com/itchio/butler/installer"
"github.com/itchio/butler/mansion"
"github.com/itchio/butler/butlerd"
"github.com/itchio/butler/cmd/elevate"
"github.com/itchio/butler/cmd/wipe"
"github.com/itchio/butler/endpoints/launch"
"github.com/itchio/smaug/runner"
"github.com/pkg/errors"
)
func Register() {
launch.RegisterLauncher(launch.LaunchStrategyNative, &Launcher{})
}
type Launcher struct{}
var _ launch.Launcher = (*Launcher)(nil)
func (l *Launcher) Do(params launch.LauncherParams) error {
consumer := params.RequestContext.Consumer
installFolder := params.InstallFolder
cwd := installFolder
_, err := filepath.Rel(installFolder, params.FullTargetPath)
if err == nil {
// if it's relative, set the cwd to the folder the
// target is in
cwd = filepath.Dir(params.FullTargetPath)
}
_, err = os.Stat(params.FullTargetPath)
if err != nil {
return errors.WithStack(err)
}
err = configureTargetIfNeeded(params)
if err != nil {
consumer.Warnf("Could not configure launch target: %s", err.Error())
}
err = fillPeInfoIfNeeded(params)
if err != nil {
consumer.Warnf("Could not determine PE info: %s", err.Error())
}
err = handlePrereqs(params)
if err != nil {
if be, ok := butlerd.AsButlerdError(err); ok {
switch butlerd.Code(be.RpcErrorCode()) {
case butlerd.CodeOperationAborted, butlerd.CodeOperationCancelled:
return be
}
}
consumer.Warnf("While handling prereqs: %+v", err)
if neterr.IsNetworkError(err) {
err = butlerd.CodeNetworkDisconnected
}
r, err := messages.PrereqsFailed.Call(params.RequestContext, butlerd.PrereqsFailedParams{
Error: err.Error(),
ErrorStack: fmt.Sprintf("%+v", err),
})
if err != nil {
return errors.WithStack(err)
}
if r.Continue {
// continue!
consumer.Warnf("Continuing after prereqs failure because user told us to")
} else {
// abort
consumer.Warnf("Giving up after prereqs failure because user asked us to")
return errors.WithStack(butlerd.CodeOperationAborted)
}
}
envMap := make(map[string]string)
for k, v := range params.Env {
envMap[k] = v
}
// give the app its own temporary directory
tempDir := filepath.Join(params.InstallFolder, ".itch", "temp")
err = os.MkdirAll(tempDir, 0755)
if err != nil {
consumer.Warnf("Could not make temporary directory: %s", err.Error())
} else {
defer wipe.Do(consumer, tempDir)
envMap["TMP"] = tempDir
envMap["TEMP"] = tempDir
consumer.Infof("Giving app temp dir (%s)", tempDir)
}
if params.Sandbox {
envMap["ITCHIO_SANDBOX"] = "1"
}
var envKeys []string
for k := range envMap {
envKeys = append(envKeys, k)
}
consumer.Infof("Environment variables passed: %s", strings.Join(envKeys, ", "))
// TODO: sanitize environment somewhat?
envBlock := os.Environ()
for k, v := range envMap {
envBlock = append(envBlock, fmt.Sprintf("%s=%s", k, v))
}
const maxLines = 40
stdout := newOutputCollector(maxLines)
stderr := newOutputCollector(maxLines)
fullTargetPath := params.FullTargetPath
name := params.FullTargetPath
args := params.Args
if params.Candidate != nil && params.Candidate.Flavor == dash.FlavorLove {
// TODO: add prereqs when that happens
args = append([]string{name}, args...)
name = "love"
fullTargetPath = "love"
consumer.Infof("We're launching a .love bundle, trying to execute with love runtime")
}
console := false
if params.Action != nil && params.Action.Console {
console = true
consumer.Infof("Console launch requested")
}
runParams := &runner.RunnerParams{
Consumer: consumer,
Ctx: params.Ctx,
Sandbox: params.Sandbox,
Console: console,
FullTargetPath: fullTargetPath,
Name: name,
Dir: cwd,
Args: args,
Env: envBlock,
Stdout: stdout,
Stderr: stderr,
InstallFolder: params.InstallFolder,
Runtime: params.Runtime,
AttachParams: l.AttachParams(params),
FirejailParams: l.FirejailParams(params),
FujiParams: l.FujiParams(params),
}
run, err := runner.GetRunner(runParams)
if err != nil {
return errors.WithStack(err)
}
err = run.Prepare()
if err != nil {
return errors.WithStack(err)
}
err = func() error {
startTime := time.Now()
messages.LaunchRunning.Notify(params.RequestContext, butlerd.LaunchRunningNotification{})
exitCode, err := interpretRunError(run.Run())
messages.LaunchExited.Notify(params.RequestContext, butlerd.LaunchExitedNotification{})
if err != nil {
return errors.WithStack(err)
}
runDuration := time.Since(startTime)
err = params.RecordPlayTime(runDuration)
if err != nil {
return errors.WithStack(err)
}
if exitCode != 0 {
var signedExitCode = int64(exitCode)
if runtime.GOOS == "windows" {
// Windows uses 32-bit unsigned integers as exit codes, although the
// command interpreter treats them as signed. If a process fails
// initialization, a Windows system error code may be returned.
signedExitCode = int64(int32(signedExitCode))
// The line above turns `4294967295` into -1
}
exeName := filepath.Base(params.FullTargetPath)
msg := fmt.Sprintf("Exit code 0x%x (%d) for (%s)", uint32(exitCode), signedExitCode, exeName)
consumer.Warnf(msg)
if runDuration.Seconds() > 10 {
consumer.Warnf("That's after running for %s, ignoring non-zero exit code", runDuration)
} else {
return errors.New(msg)
}
}
return nil
}()
if err != nil {
consumer.Errorf("Had error: %s", err.Error())
if len(stderr.Lines()) == 0 {
consumer.Errorf("No messages for standard error")
consumer.Errorf("β Standard error: empty")
} else {
consumer.Errorf("β Standard error ================")
for _, l := range stderr.Lines() {
consumer.Errorf(" %s", l)
}
consumer.Errorf("=================================")
}
if len(stdout.Lines()) == 0 {
consumer.Errorf("β Standard output: empty")
} else {
consumer.Errorf("β Standard output ===============")
for _, l := range stdout.Lines() {
consumer.Errorf(" %s", l)
}
consumer.Errorf("=================================")
}
consumer.Errorf("Relaying launch failure.")
return errors.WithStack(err)
}
return nil
}
func (l *Launcher) FirejailParams(params launch.LauncherParams) runner.FirejailParams {
name := fmt.Sprintf("firejail-%s", params.Runtime.Arch())
binaryPath := filepath.Join(params.PrereqsDir, name, "firejail")
return runner.FirejailParams{
BinaryPath: binaryPath,
}
}
func (l *Launcher) FujiParams(params launch.LauncherParams) runner.FujiParams {
consumer := params.RequestContext.Consumer
return runner.FujiParams{
Settings: mansion.GetFujiSettings(),
PerformElevatedSetup: func() error {
r, err := messages.AllowSandboxSetup.Call(params.RequestContext, butlerd.AllowSandboxSetupParams{})
if err != nil {
return errors.WithStack(err)
}
if !r.Allow {
return errors.WithStack(butlerd.CodeOperationAborted)
}
consumer.Infof("Proceeding with sandbox setup...")
res, err := installer.RunSelf(&installer.RunSelfParams{
Consumer: consumer,
Args: []string{
"--elevate",
"fuji",
"setup",
},
})
if err != nil {
return errors.WithStack(err)
}
if res.ExitCode != 0 {
if res.ExitCode == elevate.ExitCodeAccessDenied {
return errors.WithStack(butlerd.CodeOperationAborted)
}
}
err = installer.CheckExitCode(res.ExitCode, err)
if err != nil {
return errors.WithStack(err)
}
return nil
},
}
}
func (l *Launcher) AttachParams(params launch.LauncherParams) runner.AttachParams {
return runner.AttachParams{
BringWindowToForeground: func(hwnd int64) {
setWindowForeground(hwnd)
},
}
}
func configureTargetIfNeeded(params launch.LauncherParams) error {
if params.Candidate != nil {
// already configured
return nil
}
v, err := dash.Configure(params.FullTargetPath, &dash.ConfigureParams{
Consumer: params.RequestContext.Consumer,
Filter: filtering.FilterPaths,
})
if err != nil {
return errors.WithStack(err)
}
if len(v.Candidates) == 0 {
return errors.Errorf("0 candidates after configure")
}
params.Candidate = v.Candidates[0]
return nil
}
func fillPeInfoIfNeeded(params launch.LauncherParams) error {
c := params.Candidate
if c == nil {
// no candidate for some reason?
return nil
}
if c.Flavor != dash.FlavorNativeWindows {
// not an .exe, ignore
return nil
}
var err error
f, err := os.Open(params.FullTargetPath)
if err != nil {
return errors.WithStack(err)
}
defer f.Close()
params.PeInfo, err = pelican.Probe(f, &pelican.ProbeParams{
Consumer: params.RequestContext.Consumer,
})
if err != nil {
return errors.WithStack(err)
}
return nil
}
func interpretRunError(err error) (int, error) {
if err != nil {
if exitError, ok := AsExitError(err); ok {
if status, ok := exitError.Sys().(syscall.WaitStatus); ok {
return status.ExitStatus(), nil
}
}
return 127, err
}
return 0, nil
}
type causer interface {
Cause() error
}
func AsExitError(err error) (*exec.ExitError, bool) {
if err == nil {
return nil, false
}
if se, ok := err.(causer); ok {
return AsExitError(se.Cause())
}
if ee, ok := err.(*exec.ExitError); ok {
return ee, true
}
return nil, false
}