44 "context"
55 "errors"
66 "fmt"
7- "io"
87 "os"
98 "strings"
9+ "sync"
1010 "time"
1111
1212 "github.com/bitxeno/atvloadly/internal/app"
@@ -16,9 +16,14 @@ import (
1616)
1717
1818type LoginManager struct {
19+ // Serializes attempts on this WebSocket to protect the shared output buffer.
20+ runMu sync.Mutex
21+ // Protects the currently active login subprocess and its input pipe.
22+ stateMu sync.Mutex
23+
1924 outputStdout * outputWriter
2025
21- stdin io. WriteCloser
26+ stdin * os. File
2227
2328 cancel context.CancelFunc
2429 em * event.Manager
@@ -34,26 +39,43 @@ func NewLoginManager() *LoginManager {
3439}
3540
3641func (t * LoginManager ) Start (ctx context.Context , account , password string ) error {
42+ if ! t .runMu .TryLock () {
43+ return errors .New ("login already in progress" )
44+ }
45+ defer t .runMu .Unlock ()
3746 t .outputStdout .Reset ()
3847
3948 // set execute timeout 10 minutes
4049 timeout := 10 * time .Minute
4150 ctx , cancel := context .WithTimeout (ctx , timeout )
42- if t .cancel != nil {
43- t .cancel ()
44- }
51+ t .stateMu .Lock ()
4552 t .cancel = cancel
53+ t .stateMu .Unlock ()
54+ defer func () {
55+ t .stateMu .Lock ()
56+ t .cancel = nil
57+ t .stateMu .Unlock ()
58+ cancel ()
59+ }()
4660
4761 stdinReader , stdinWriter , err := os .Pipe ()
4862 if err != nil {
4963 log .Err (err ).Msg ("Error creating stdin pipe: " )
5064 return err
5165 }
66+ t .stateMu .Lock ()
5267 t .stdin = stdinWriter
68+ t .stateMu .Unlock ()
5369 defer func () {
70+ // Remove the active reference before closing the specific pipe for
71+ // this attempt. In-flight os.File writes return an error on close.
72+ t .stateMu .Lock ()
73+ if t .stdin == stdinWriter {
74+ t .stdin = nil
75+ }
76+ t .stateMu .Unlock ()
77+ _ = stdinWriter .Close ()
5478 _ = stdinReader .Close ()
55- _ = t .stdin .Close ()
56- t .stdin = nil
5779 }()
5880
5981 err = execx .CommandContext (ctx , "plumesign" , "account" , "login" , "-u" , account , "-p" , password ).
@@ -76,9 +98,12 @@ func (t *LoginManager) Start(ctx context.Context, account, password string) erro
7698}
7799
78100func (t * LoginManager ) Close () {
79- if t .cancel != nil {
80- t .cancel ()
81- t .cancel = nil
101+ t .stateMu .Lock ()
102+ cancel := t .cancel
103+ t .cancel = nil
104+ t .stateMu .Unlock ()
105+ if cancel != nil {
106+ cancel ()
82107 }
83108 if t .em != nil {
84109 _ = t .em .CloseWait ()
@@ -93,7 +118,14 @@ func (t *LoginManager) OnOutput(fn func(string)) {
93118}
94119
95120func (t * LoginManager ) Write (p []byte ) {
96- _ , _ = t .stdin .Write (p )
121+ t .stateMu .Lock ()
122+ writer := t .stdin
123+ t .stateMu .Unlock ()
124+ // A late 2FA reply is harmless after the subprocess exits. Never keep
125+ // stateMu across Write: an OS pipe can block until its reader exits.
126+ if writer != nil {
127+ _ , _ = writer .Write (p )
128+ }
97129}
98130
99131func (t * LoginManager ) ErrorLog () string {
0 commit comments