forked from perkeep/perkeep
/
android.go
321 lines (284 loc) · 7.64 KB
/
android.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
/*
Copyright 2013 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Hacks for running a camlistore commands as a child process on Android.
package client
import (
"bufio"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"sync"
"time"
"camlistore.org/pkg/blobref"
"camlistore.org/pkg/blobserver"
"camlistore.org/pkg/schema"
)
// TODO(mpl): Integrate all that better. move the glob vars into
// the client? More docs too.
var detectOnce sync.Once
var onAndroidCache bool
func dirExists(f string) bool {
fi, err := os.Stat(f)
return err == nil && fi.IsDir()
}
func initOnAndroid() {
// Good enough heuristic. Suggestions welcome.
onAndroidCache = dirExists("/data/data") && dirExists("/system/etc")
}
func onAndroid() bool {
detectOnce.Do(initOnAndroid)
return onAndroidCache
}
var pingRx = regexp.MustCompile(`\((.+?)\)`)
type namedInt struct {
name string
sync.Mutex
val int64
}
func (ni *namedInt) Incr(delta int64) {
ni.Lock()
ni.val += delta
nv := ni.val
ni.Unlock()
Androidf("STAT %s %d\n", ni.name, nv)
}
var (
statDNSStart = &namedInt{name: "dns_start"}
statDNSDone = &namedInt{name: "dns_done"}
statTCPStart = &namedInt{name: "tcp_start"}
statTCPStarted = &namedInt{name: "tcp_started"}
statTCPFail = &namedInt{name: "tcp_fail"}
statTCPDone = &namedInt{name: "tcp_done"}
statTCPWrites = &namedInt{name: "tcp_write_byte"}
statTCPWrote = &namedInt{name: "tcp_wrote_byte"}
statTCPReads = &namedInt{name: "tcp_read_byte"}
statHTTPStart = &namedInt{name: "http_start"}
statHTTPResHeaders = &namedInt{name: "http_res_headers"}
statBlobUploaded = &namedInt{name: "blob_uploaded"}
statBlobExisted = &namedInt{name: "blob_existed"}
statFileUploaded = &namedInt{name: "file_uploaded"}
statFileExisted = &namedInt{name: "file_existed"}
)
type statTrackingConn struct {
net.Conn
}
func (c statTrackingConn) Write(p []byte) (n int, err error) {
statTCPWrites.Incr(int64(len(p)))
n, err = c.Conn.Write(p)
statTCPWrote.Incr(int64(n))
return
}
func (c statTrackingConn) Read(p []byte) (n int, err error) {
n, err = c.Conn.Read(p)
statTCPReads.Incr(int64(n))
return
}
var (
dnsMu sync.Mutex
dnsCache = make(map[string]string)
)
func androidLookupHost(host string) string {
dnsMu.Lock()
v, ok := dnsCache[host]
dnsMu.Unlock()
if ok {
return v
}
statDNSStart.Incr(1)
defer statDNSDone.Incr(1)
// Android has no "dig" or "host" tool, so use "ping -c 1". Ghetto.
// $ ping -c 1 google.com
// PING google.com (74.125.224.64) 56(84) bytes of data.
c := make(chan string, 1)
go func() {
cmd := exec.Command("/system/bin/ping", "-c", "1", host)
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
defer stdout.Close()
if err := cmd.Start(); err != nil {
log.Printf("Error resolving %q with ping: %v", host, err)
c <- host
return
}
defer func() {
if p := cmd.Process; p != nil {
p.Kill()
}
}()
br := bufio.NewReader(stdout)
line, err := br.ReadString('\n')
if err != nil {
log.Printf("Failed to resolve %q with ping", host)
c <- host
return
}
if m := pingRx.FindStringSubmatch(line); m != nil {
ip := m[1]
dnsMu.Lock()
dnsCache[host] = ip
dnsMu.Unlock()
c <- ip
return
}
log.Printf("Failed to resolve %q with ping", host)
c <- host
}()
return <-c
return v
}
type AndroidStatsTransport struct {
Rt http.RoundTripper
}
func (t AndroidStatsTransport) RoundTrip(req *http.Request) (res *http.Response, err error) {
statHTTPStart.Incr(1)
res, err = t.Rt.RoundTrip(req)
statHTTPResHeaders.Incr(1)
// TODO: track per-response code stats, and also track when body done being read.
return
}
func androidDial(network, addr string) (net.Conn, error) {
// Temporary laziness hack, avoiding doing a
// cross-compiled Android cgo build.
// Without cgo, package net uses
// /etc/resolv.conf (not available on
// Android). We really want a cgo binary to
// use Android's DNS cache, but it's kinda
// hard/impossible to cross-compile for now.
statTCPStart.Incr(1)
host, port, err := net.SplitHostPort(addr)
if err != nil {
statTCPFail.Incr(1)
return nil, fmt.Errorf("couldn't split %q", addr)
}
c, err := net.Dial(network, net.JoinHostPort(androidLookupHost(host), port))
if err != nil {
statTCPFail.Incr(1)
return nil, err
}
statTCPStarted.Incr(1)
return statTrackingConn{Conn: c}, err
}
func androidTLSConfig() (*tls.Config, error) {
if !onAndroid() {
return nil, nil
}
certDir := "/system/etc/security/cacerts"
fi, err := os.Stat(certDir)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf("%q not a dir", certDir)
}
pool := x509.NewCertPool()
cfg := &tls.Config{RootCAs: pool}
f, err := os.Open(certDir)
if err != nil {
return nil, err
}
defer f.Close()
names, _ := f.Readdirnames(-1)
for _, name := range names {
pem, err := ioutil.ReadFile(filepath.Join(certDir, name))
if err != nil {
return nil, err
}
pool.AppendCertsFromPEM(pem)
}
return cfg, nil
}
// TODO(mpl): distinguish CAMPUT, CAMGET, etc
var androidOutput = os.Getenv("CAMPUT_ANDROID_OUTPUT") != ""
func AndroidOutput() bool {
return androidOutput
}
var androidOutMu sync.Mutex
func Androidf(format string, args ...interface{}) {
androidOutMu.Lock()
defer androidOutMu.Unlock()
fmt.Printf(format, args...)
}
func NoteFileUploaded(fullPath string, uploaded bool) {
if !AndroidOutput() {
return
}
if uploaded {
statFileUploaded.Incr(1)
} else {
statFileExisted.Incr(1)
}
Androidf("FILE_UPLOADED %s\n", fullPath)
}
// androidStatusReceiver is a blobserver.StatReceiver wrapper that
// reports the full filename path and size of uploaded blobs.
// The android app wrapping camput watches stdout for this, for progress bars.
type AndroidStatusReceiver struct {
Sr blobserver.StatReceiver
Path string
}
func (asr AndroidStatusReceiver) noteChunkOnServer(sb blobref.SizedBlobRef) {
Androidf("CHUNK_UPLOADED %d %s %s\n", sb.Size, sb.BlobRef, asr.Path)
}
func (asr AndroidStatusReceiver) ReceiveBlob(blob *blobref.BlobRef, source io.Reader) (blobref.SizedBlobRef, error) {
// Sniff the first 1KB of it and don't print the stats if it looks like it was just a schema
// blob. We won't update the progress bar for that yet.
var buf [1024]byte
contents := buf[:0]
sb, err := asr.Sr.ReceiveBlob(blob, io.TeeReader(source, writeUntilSliceFull{&contents}))
if err == nil && !schema.LikelySchemaBlob(contents) {
statBlobUploaded.Incr(1)
asr.noteChunkOnServer(sb)
}
return sb, err
}
func (asr AndroidStatusReceiver) StatBlobs(dest chan<- blobref.SizedBlobRef, blobs []*blobref.BlobRef, wait time.Duration) error {
midc := make(chan blobref.SizedBlobRef)
errc := make(chan error, 1)
go func() {
err := asr.Sr.StatBlobs(midc, blobs, wait)
errc <- err
close(midc)
}()
for sb := range midc {
asr.noteChunkOnServer(sb)
statBlobExisted.Incr(1)
dest <- sb
}
return <-errc
}
type writeUntilSliceFull struct {
s *[]byte
}
func (w writeUntilSliceFull) Write(p []byte) (n int, err error) {
s := *w.s
l := len(s)
growBy := cap(s) - l
if growBy > len(p) {
growBy = len(p)
}
s = s[0 : l+growBy]
copy(s[l:], p)
*w.s = s
return len(p), nil
}