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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
|
package main
// adbd: a small adb daemon, so the stock `adb` client works against the
// tolino OS (shell, push/pull, reboot). Android's adbd needs half of AOSP;
// the protocol itself is small. References: AOSP adb/docs/dev/protocol.md,
// sync.md, daemon/usb_ffs.cpp, daemon/auth.cpp.
//
// Transport: the USB function is a functionfs instance (configfs gadget,
// see usbGadget); adbd writes the descriptors to ep0, then reads and writes
// adb messages on ep1 (OUT) and ep2 (IN).
//
// Auth: the host's adbkey.pub keys in /etc/adb_keys (in the generation, so
// it is part of the build). Without a matching key, nothing but CNXN/AUTH
// is answered.
import (
"bufio"
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/sys/unix"
)
const (
aCNXN = 0x4e584e43
aAUTH = 0x48545541
aOPEN = 0x4e45504f
aOKAY = 0x59414b4f
aCLSE = 0x45534c43
aWRTE = 0x45545257
adbVersion = 0x01000001 // skip-checksum capable
maxPayload = 256 * 1024
authToken = 1
authSignature = 2
authPublicKey = 3
ffsDir = "/dev/usb-ffs/adb"
adbKeys = "/etc/adb_keys"
// busybox is for adb shell only, so it is on no other PATH. /sbin comes
// first: its poweroff, reboot and halt are s6-linux-init's, which talk
// to our PID 1 correctly; busybox's do not (tolino.7, "Shutting down").
shellPath = "/opt/busybox/bin/sh"
shellEnvPath = "PATH=/sbin:/bin:/opt/busybox/bin"
deviceName = "tolino"
)
type message struct {
cmd, arg0, arg1 uint32
data []byte
}
type conn struct {
in io.Reader // ep1, host -> device
out io.Writer // ep2, device -> host
wmu sync.Mutex
authed bool
token []byte
maxData uint32
streams map[uint32]*stream
smu sync.Mutex
nextID uint32
keys []*rsa.PublicKey
checksum bool
}
func adbd(args []string) error {
keys, err := loadAdbKeys(adbKeys)
if err != nil {
return err
}
// ep0 stays open for the daemon's whole life: closing it removes the
// USB function, so the device would vanish from the host and
// re-enumerate. That is what happened when every endpoint error tore
// everything down; the host resets the bus right after enumeration, and
// on `adb kill-server`, and the bulk endpoints report ECONNRESET.
ep0, err := os.OpenFile(ffsDir+"/ep0", os.O_RDWR, 0)
if err != nil {
return err
}
if _, err := ep0.Write(ffsDescriptors()); err != nil {
return fmt.Errorf("writing descriptors: %w", err)
}
if _, err := ep0.Write(ffsStrings()); err != nil {
return fmt.Errorf("writing strings: %w", err)
}
// Descriptors are in: the function is ready, so bind the gadget to the
// UDC now (it cannot be bound before ep0 has descriptors).
if err := gadgetBind(); err != nil {
return err
}
enabled := make(chan struct{}, 1)
go ep0Events(ep0, enabled)
// Only the bulk endpoints are re-opened per host session, as Android's
// adbd does.
for {
if err := serveUSB(keys, enabled); err != nil {
fmt.Fprintf(os.Stderr, "adbd: %v; waiting for the host\n", err)
}
}
}
// functionfs ep0 event types (linux/usb/functionfs.h).
const (
ffsBind = 0
ffsUnbind = 1
ffsEnable = 2
ffsDisable = 3
ffsSetup = 4
ffsSuspend = 5
ffsResume = 6
)
// ep0Events reads functionfs events (12 bytes each: 8 setup bytes, type, 3
// padding) for the life of the daemon, and signals each ENABLE: the host
// has configured the device, so the bulk endpoints work again.
func ep0Events(ep0 *os.File, enabled chan<- struct{}) {
buf := make([]byte, 12*4)
for {
n, err := ep0.Read(buf)
if err != nil {
fmt.Fprintf(os.Stderr, "adbd: ep0: %v\n", err)
time.Sleep(time.Second)
continue
}
for i := 0; i+12 <= n; i += 12 {
if buf[i+8] == ffsEnable {
select {
case enabled <- struct{}{}:
default:
}
}
}
}
}
// serveUSB serves one host session on the bulk endpoints, until the host
// goes away (bus reset, cable pulled, adb kill-server). It waits for the
// function to be enabled if the endpoints are not usable yet.
func serveUSB(keys []*rsa.PublicKey, enabled <-chan struct{}) error {
epOut, err := os.OpenFile(ffsDir+"/ep1", os.O_RDONLY, 0)
if err != nil {
return err
}
defer epOut.Close()
epIn, err := os.OpenFile(ffsDir+"/ep2", os.O_WRONLY, 0)
if err != nil {
return err
}
defer epIn.Close()
c := &conn{
in: bufio.NewReaderSize(epOut, maxPayload+24),
out: epIn,
keys: keys,
streams: map[uint32]*stream{},
maxData: 4096,
checksum: true,
}
err = c.serve()
c.closeAll()
// After a reset the endpoints fail until the host configures the
// device again; wait for that (or a timeout, in case the ENABLE event
// came before we got here) instead of spinning on errors.
select {
case <-enabled:
case <-time.After(2 * time.Second):
}
return err
}
// closeAll ends every stream of a session that is gone, so shells and
// transfers of the old session do not linger.
func (c *conn) closeAll() {
c.smu.Lock()
ss := make([]*stream, 0, len(c.streams))
for _, s := range c.streams {
ss = append(ss, s)
}
c.smu.Unlock()
for _, s := range ss {
s.close(false)
}
}
func (c *conn) serve() error {
for {
m, err := c.read()
if err != nil {
return err
}
switch m.cmd {
case aCNXN:
c.maxData = min(m.arg1, maxPayload)
c.checksum = m.arg0 < adbVersion
if c.authed {
c.sendCNXN()
continue
}
c.sendToken()
case aAUTH:
c.handleAuth(m)
case aOPEN:
if !c.authed {
continue
}
c.open(m)
case aOKAY:
if s := c.stream(m.arg1); s != nil {
s.remote = m.arg0
s.ready()
}
case aWRTE:
if s := c.stream(m.arg1); s != nil {
c.send(aOKAY, s.local, m.arg0, nil)
s.input(m.data)
}
case aCLSE:
if s := c.stream(m.arg1); s != nil {
s.close(false)
}
}
}
}
func (c *conn) read() (message, error) {
var h [24]byte
if _, err := io.ReadFull(c.in, h[:]); err != nil {
return message{}, err
}
le := binary.LittleEndian
m := message{cmd: le.Uint32(h[0:]), arg0: le.Uint32(h[4:]), arg1: le.Uint32(h[8:])}
n := le.Uint32(h[12:])
if le.Uint32(h[20:]) != m.cmd^0xffffffff {
return m, errors.New("bad message magic")
}
if n > maxPayload {
return m, fmt.Errorf("payload too large: %d", n)
}
m.data = make([]byte, n)
if _, err := io.ReadFull(c.in, m.data); err != nil {
return m, err
}
return m, nil
}
func (c *conn) send(cmd, arg0, arg1 uint32, data []byte) {
var h [24]byte
le := binary.LittleEndian
le.PutUint32(h[0:], cmd)
le.PutUint32(h[4:], arg0)
le.PutUint32(h[8:], arg1)
le.PutUint32(h[12:], uint32(len(data)))
// data_crc32 is, despite its name, a byte sum; only peers older than
// A_VERSION_SKIP_CHECKSUM check it.
if c.checksum {
var sum uint32
for _, b := range data {
sum += uint32(b)
}
le.PutUint32(h[16:], sum)
}
le.PutUint32(h[20:], cmd^0xffffffff)
c.wmu.Lock()
defer c.wmu.Unlock()
// Header and payload are separate USB transfers, as adbd does.
c.out.Write(h[:])
if len(data) > 0 {
c.out.Write(data)
}
}
func (c *conn) sendCNXN() {
banner := "device::ro.product.name=" + deviceName +
";ro.product.model=tolino_vision_6;ro.product.device=vision6;" +
"features=shell_v2,cmd,stat_v2,ls_v2,fixed_push_mkdir,sendrecv_v2"
c.send(aCNXN, adbVersion, maxPayload, []byte(banner))
}
func (c *conn) sendToken() {
c.token = make([]byte, 20)
rand.Read(c.token)
c.send(aAUTH, authToken, 0, c.token)
}
func (c *conn) handleAuth(m message) {
switch m.arg0 {
case authSignature:
for _, k := range c.keys {
// adb signs the 20-byte token as if it were a SHA-1 digest.
if rsa.VerifyPKCS1v15(k, crypto.SHA1, c.token, m.data) == nil {
c.authed = true
c.sendCNXN()
return
}
}
c.sendToken()
case authPublicKey:
// Unknown key: no on-screen confirmation here, keys come only from
// the build. Keep asking; `adb devices` shows "unauthorized".
fmt.Fprintf(os.Stderr, "adbd: rejected unknown key %s\n", strings.TrimSpace(string(bytes.TrimRight(m.data, "\x00"))))
}
}
// loadAdbKeys parses adb_keys: one "<base64 android pubkey> <comment>" per
// line. The binary format (android_pubkey.cpp) is: u32 modulus size in
// words, u32 n0inv, modulus (LE), rr (LE), u32 exponent.
func loadAdbKeys(path string) ([]*rsa.PublicKey, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var keys []*rsa.PublicKey
for _, line := range strings.Split(string(b), "\n") {
f := strings.Fields(line)
if len(f) == 0 {
continue
}
raw, err := base64.StdEncoding.DecodeString(f[0])
if err != nil || len(raw) < 12 {
continue
}
words := binary.LittleEndian.Uint32(raw)
n := int(words) * 4
if len(raw) < 8+2*n+4 {
continue
}
mod := make([]byte, n)
for i := range mod {
mod[i] = raw[8+n-1-i] // little-endian -> big-endian
}
e := binary.LittleEndian.Uint32(raw[8+2*n:])
keys = append(keys, &rsa.PublicKey{N: new(big.Int).SetBytes(mod), E: int(e)})
}
if len(keys) == 0 {
return nil, fmt.Errorf("%s: no keys", path)
}
return keys, nil
}
// --- streams ---------------------------------------------------------------
type stream struct {
c *conn
local uint32
remote uint32
okay chan struct{} // one token per OKAY: permission to send one WRTE
in *io.PipeWriter
once sync.Once
}
func (c *conn) stream(id uint32) *stream {
c.smu.Lock()
defer c.smu.Unlock()
return c.streams[id]
}
func (c *conn) newStream(remote uint32) (*stream, *io.PipeReader) {
c.smu.Lock()
defer c.smu.Unlock()
c.nextID++
pr, pw := io.Pipe()
s := &stream{c: c, local: c.nextID, remote: remote, okay: make(chan struct{}, 1), in: pw}
c.streams[s.local] = s
return s, pr
}
func (s *stream) ready() {
select {
case s.okay <- struct{}{}:
default:
}
}
func (s *stream) input(b []byte) { s.in.Write(b) }
// Write sends data to the host, one WRTE per maxData chunk, each waiting
// for the host's OKAY as the protocol requires.
func (s *stream) Write(b []byte) (int, error) {
n := 0
for len(b) > 0 {
chunk := b[:min(len(b), int(s.c.maxData))]
if _, ok := <-s.okay; !ok {
return n, io.ErrClosedPipe
}
s.c.send(aWRTE, s.local, s.remote, chunk)
n += len(chunk)
b = b[len(chunk):]
}
return n, nil
}
func (s *stream) close(notify bool) {
s.once.Do(func() {
s.c.smu.Lock()
delete(s.c.streams, s.local)
s.c.smu.Unlock()
s.in.Close()
close(s.okay)
if notify {
s.c.send(aCLSE, s.local, s.remote, nil)
}
})
}
func (c *conn) open(m message) {
name := strings.TrimRight(string(m.data), "\x00")
s, in := c.newStream(m.arg0)
c.send(aOKAY, s.local, s.remote, nil)
s.ready() // OPEN implies READY from the host
go func() {
defer s.close(true)
if err := runService(name, s, in); err != nil {
fmt.Fprintf(s, "adbd: %v\n", err)
}
}()
}
func runService(name string, out io.Writer, in io.Reader) error {
switch {
case strings.HasPrefix(name, "shell"):
return shellService(strings.TrimPrefix(name, "shell"), out, in)
case strings.HasPrefix(name, "exec:"):
return execService(strings.TrimPrefix(name, "exec:"), out, in)
case name == "sync:":
return syncService(out, in)
case strings.HasPrefix(name, "reboot:"):
arg := strings.TrimPrefix(name, "reboot:")
unix.Sync()
if arg != "" {
rebootTo(arg)
}
return unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
}
return fmt.Errorf("unsupported service %q", name)
}
// --- shell -----------------------------------------------------------------
// shellService implements "shell[,args]:command". With shell_v2 (which we
// advertise), the client wraps stdin/stdout/stderr/exit in packets:
// u8 id, u32 LE length, data. ids: 0 stdin, 1 stdout, 2 stderr, 3 exit,
// 4 close-stdin, 5 window-size.
func shellService(spec string, out io.Writer, in io.Reader) error {
opts, command, _ := strings.Cut(spec, ":")
v2 := strings.Contains(opts, "v2")
pty := command == "" && !strings.Contains(opts, "raw") || strings.Contains(opts, "pty")
argv := []string{shellPath}
if command != "" {
argv = append(argv, "-c", command)
} else {
argv = append(argv, "-l")
}
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Env = []string{shellEnvPath, "HOME=/root", "TERM=xterm", "SHELL=" + shellPath}
cmd.Dir = "/"
for _, kv := range strings.Split(opts, ",") {
if strings.HasPrefix(kv, "TERM=") {
cmd.Env = append(cmd.Env, kv)
}
}
var stdout, stderr io.Writer = out, out
var stdinW io.WriteCloser
var ptyMaster *os.File
var wmu sync.Mutex
packet := func(id byte, b []byte) {
wmu.Lock()
defer wmu.Unlock()
var h [5]byte
h[0] = id
binary.LittleEndian.PutUint32(h[1:], uint32(len(b)))
out.Write(append(h[:], b...))
}
if v2 {
stdout = writerFunc(func(b []byte) (int, error) { packet(1, b); return len(b), nil })
stderr = writerFunc(func(b []byte) (int, error) { packet(2, b); return len(b), nil })
}
if pty {
m, s, err := openPty()
if err != nil {
return err
}
ptyMaster = m
cmd.Stdin, cmd.Stdout, cmd.Stderr = s, s, s
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
if err := cmd.Start(); err != nil {
return err
}
s.Close()
stdinW = m
go io.Copy(stdout, m)
} else {
w, err := cmd.StdinPipe()
if err != nil {
return err
}
stdinW = w
cmd.Stdout, cmd.Stderr = stdout, stderr
if err := cmd.Start(); err != nil {
return err
}
}
go func() {
if !v2 {
io.Copy(stdinW, in)
stdinW.Close()
return
}
r := bufio.NewReader(in)
for {
var h [5]byte
if _, err := io.ReadFull(r, h[:]); err != nil {
stdinW.Close()
return
}
b := make([]byte, binary.LittleEndian.Uint32(h[1:]))
if _, err := io.ReadFull(r, b); err != nil {
stdinW.Close()
return
}
switch h[0] {
case 0:
stdinW.Write(b)
case 4:
stdinW.Close()
case 5:
if ptyMaster != nil {
setWinsize(ptyMaster, string(b))
}
}
}
}()
err := cmd.Wait()
code := 0
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) {
code = ee.ExitCode()
} else {
code = 1
}
}
if ptyMaster != nil {
// Let the reader drain what the shell wrote before it exited.
time.Sleep(50 * time.Millisecond)
}
if v2 {
packet(3, []byte{byte(code)})
}
return nil
}
func execService(command string, out io.Writer, in io.Reader) error {
cmd := exec.Command(shellPath, "-c", command)
cmd.Env = []string{shellEnvPath, "HOME=/root"}
cmd.Stdin, cmd.Stdout, cmd.Stderr = in, out, out
return cmd.Run()
}
type writerFunc func([]byte) (int, error)
func (f writerFunc) Write(b []byte) (int, error) { return f(b) }
func openPty() (master, slave *os.File, err error) {
m, err := os.OpenFile("/dev/ptmx", os.O_RDWR|syscall.O_NOCTTY, 0)
if err != nil {
return nil, nil, err
}
if err := unix.IoctlSetPointerInt(int(m.Fd()), unix.TIOCSPTLCK, 0); err != nil {
m.Close()
return nil, nil, err
}
n, err := unix.IoctlGetInt(int(m.Fd()), unix.TIOCGPTN)
if err != nil {
m.Close()
return nil, nil, err
}
s, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", n), os.O_RDWR|syscall.O_NOCTTY, 0)
if err != nil {
m.Close()
return nil, nil, err
}
return m, s, nil
}
// setWinsize applies a shell_v2 window-size packet: "rowsxcols,xxypx".
func setWinsize(f *os.File, spec string) {
var rows, cols, x, y uint16
fmt.Sscanf(spec, "%dx%d,%dx%d", &rows, &cols, &x, &y)
ws := unix.Winsize{Row: rows, Col: cols, Xpixel: x, Ypixel: y}
unix.IoctlSetWinsize(int(f.Fd()), unix.TIOCSWINSZ, &ws)
}
// --- sync (push/pull) ------------------------------------------------------
func syncService(out io.Writer, in io.Reader) error {
r := bufio.NewReader(in)
le := binary.LittleEndian
resp := func(id string, n uint32, data []byte) {
var h [8]byte
copy(h[:], id)
le.PutUint32(h[4:], n)
out.Write(append(h[:], data...))
}
fail := func(msg string) { resp("FAIL", uint32(len(msg)), []byte(msg)) }
for {
var h [8]byte
if _, err := io.ReadFull(r, h[:]); err != nil {
return nil
}
id, n := string(h[:4]), le.Uint32(h[4:])
if id == "QUIT" {
return nil
}
buf := make([]byte, n)
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
arg := string(buf)
switch id {
case "STAT", "LST2", "STA2":
var st unix.Stat_t
err := unix.Lstat(arg, &st)
if id == "STAT" {
var b [16]byte
copy(b[:], "STAT")
if err == nil {
le.PutUint32(b[4:], st.Mode)
le.PutUint32(b[8:], uint32(st.Size))
le.PutUint32(b[12:], uint32(st.Mtim.Sec))
}
out.Write(b[:])
continue
}
out.Write(statV2(id, &st, err))
case "LIST", "LIS2":
ents, _ := os.ReadDir(arg)
for _, e := range ents {
var st unix.Stat_t
err := unix.Lstat(filepath.Join(arg, e.Name()), &st)
if id == "LIST" {
var b [20]byte
copy(b[:], "DENT")
le.PutUint32(b[4:], st.Mode)
le.PutUint32(b[8:], uint32(st.Size))
le.PutUint32(b[12:], uint32(st.Mtim.Sec))
le.PutUint32(b[16:], uint32(len(e.Name())))
out.Write(append(b[:], e.Name()...))
} else {
b := statV2("DNT2", &st, err)
var l [4]byte
le.PutUint32(l[:], uint32(len(e.Name())))
out.Write(append(append(b, l[:]...), e.Name()...))
}
}
resp("DONE", 0, make([]byte, map[bool]int{true: 8, false: 64}[id == "LIST"]))
case "SEND", "SND2":
path, mode := arg, os.FileMode(0o644)
if id == "SND2" {
// SND2 is followed by another request carrying mode and flags.
var x [12]byte
io.ReadFull(r, x[:])
mode = os.FileMode(le.Uint32(x[4:]) & 0o7777)
} else if i := strings.LastIndexByte(arg, ','); i >= 0 {
path = arg[:i]
var m uint32
fmt.Sscanf(arg[i+1:], "%d", &m)
mode = os.FileMode(m & 0o7777)
}
os.MkdirAll(filepath.Dir(path), 0o755)
tmp := path + ".adbtmp"
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
var werr error = err
for {
var dh [8]byte
if _, err := io.ReadFull(r, dh[:]); err != nil {
return err
}
dn := le.Uint32(dh[4:])
if string(dh[:4]) == "DONE" {
if f != nil {
f.Close()
}
if werr == nil {
werr = os.Rename(tmp, path)
os.Chtimes(path, time.Unix(int64(dn), 0), time.Unix(int64(dn), 0))
} else {
os.Remove(tmp)
}
break
}
chunk := make([]byte, dn)
if _, err := io.ReadFull(r, chunk); err != nil {
return err
}
if werr == nil {
_, werr = f.Write(chunk)
}
}
if werr != nil {
fail(werr.Error())
} else {
resp("OKAY", 0, nil)
}
case "RECV", "RCV2":
if id == "RCV2" {
var x [8]byte
io.ReadFull(r, x[:])
}
f, err := os.Open(arg)
if err != nil {
fail(err.Error())
continue
}
chunk := make([]byte, 64*1024)
for {
k, err := f.Read(chunk)
if k > 0 {
resp("DATA", uint32(k), chunk[:k])
}
if err != nil {
break
}
}
f.Close()
resp("DONE", 0, nil)
default:
fail("unsupported sync request " + id)
return nil
}
}
}
// statV2 is the 72-byte sync_stat_v2 (also the head of sync_dent_v2).
func statV2(id string, st *unix.Stat_t, err error) []byte {
b := make([]byte, 72)
le := binary.LittleEndian
copy(b, id)
if err != nil {
if errno, ok := err.(unix.Errno); ok {
le.PutUint32(b[4:], uint32(errno))
} else {
le.PutUint32(b[4:], uint32(unix.EIO))
}
return b
}
le.PutUint64(b[8:], uint64(st.Dev))
le.PutUint64(b[16:], uint64(st.Ino))
le.PutUint32(b[24:], st.Mode)
le.PutUint32(b[28:], uint32(st.Nlink))
le.PutUint32(b[32:], st.Uid)
le.PutUint32(b[36:], st.Gid)
le.PutUint64(b[40:], uint64(st.Size))
le.PutUint64(b[48:], uint64(st.Atim.Sec))
le.PutUint64(b[56:], uint64(st.Mtim.Sec))
le.PutUint64(b[64:], uint64(st.Ctim.Sec))
return b
}
// --- functionfs descriptors --------------------------------------------------
// ffsDescriptors builds the FUNCTIONFS_DESCRIPTORS_MAGIC_V2 blob with full
// and high speed descriptors for one interface (class ff/42/01, adb's) with
// two bulk endpoints: 1 OUT (host->device), 2 IN. No SuperSpeed: the UDC is
// USB 2.0.
func ffsDescriptors() []byte {
var b bytes.Buffer
le := binary.LittleEndian
intf := func(w *bytes.Buffer) {
w.Write([]byte{9, 4, 0, 0, 2, 0xff, 0x42, 0x01, 1})
}
ep := func(w *bytes.Buffer, addr byte, maxPacket uint16) {
w.Write([]byte{7, 5, addr, 2})
binary.Write(w, le, maxPacket)
w.WriteByte(0)
}
var fs, hs bytes.Buffer
intf(&fs)
ep(&fs, 0x01, 64)
ep(&fs, 0x82, 64)
intf(&hs)
ep(&hs, 0x01, 512)
ep(&hs, 0x82, 512)
const magicV2 = 3
const hasFS, hasHS = 1, 2
body := append(fs.Bytes(), hs.Bytes()...)
binary.Write(&b, le, uint32(magicV2))
binary.Write(&b, le, uint32(12+8+len(body))) // header + counts + descs
binary.Write(&b, le, uint32(hasFS|hasHS))
binary.Write(&b, le, uint32(3)) // fs_count
binary.Write(&b, le, uint32(3)) // hs_count
b.Write(body)
return b.Bytes()
}
func ffsStrings() []byte {
var b bytes.Buffer
le := binary.LittleEndian
str := []byte("ADB Interface\x00")
binary.Write(&b, le, uint32(2)) // FUNCTIONFS_STRINGS_MAGIC
binary.Write(&b, le, uint32(16+2+len(str))) // length
binary.Write(&b, le, uint32(1)) // str_count
binary.Write(&b, le, uint32(1)) // lang_count
binary.Write(&b, le, uint16(0x0409)) // en-US
b.Write(str)
return b.Bytes()
}
|