1// TODO: replace this with a shell/python script.
2
3/* a simple test program, connects to ADB server, and opens a track-devices session */
4#include <netdb.h>
5#include <sys/socket.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <errno.h>
9#include <memory.h>
10
11#include <base/file.h>
12
13static void
14panic( const char*  msg )
15{
16    fprintf(stderr, "PANIC: %s: %s\n", msg, strerror(errno));
17    exit(1);
18}
19
20int main(int argc, char* argv[]) {
21    const char* request = "host:track-devices";
22
23    if (argv[1] && strcmp(argv[1], "--jdwp") == 0) {
24        request = "track-jdwp";
25    }
26
27    int                  ret;
28    struct sockaddr_in   server;
29    char                 buffer[1024];
30
31    memset( &server, 0, sizeof(server) );
32    server.sin_family      = AF_INET;
33    server.sin_port        = htons(5037);
34    server.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
35
36    int s = socket( PF_INET, SOCK_STREAM, 0 );
37    ret = connect( s, (struct sockaddr*) &server, sizeof(server) );
38    if (ret < 0) panic( "could not connect to server" );
39
40    /* send the request */
41    int len = snprintf(buffer, sizeof(buffer), "%04zx%s", strlen(request), request);
42    if (!android::base::WriteFully(s, buffer, len))
43        panic( "could not send request" );
44
45    /* read the OKAY answer */
46    if (!android::base::ReadFully(s, buffer, 4))
47        panic( "could not read request" );
48
49    printf( "server answer: %.*s\n", 4, buffer );
50
51    /* now loop */
52    while (true) {
53        char  head[5] = "0000";
54
55        if (!android::base::ReadFully(s, head, 4))
56            panic("could not read length");
57
58        int len;
59        if (sscanf(head, "%04x", &len) != 1 )
60            panic("could not decode length");
61
62        if (!android::base::ReadFully(s, buffer, len))
63            panic("could not read data");
64
65        printf( "received header %.*s (%d bytes):\n%.*s", 4, head, len, len, buffer );
66    }
67    close(s);
68}
69