aboutsummaryrefslogtreecommitdiffstats
path: root/android/protocol/core-connection.c
blob: 6de5386aee0de6d346bac4daf4c5cef1207330e4 (plain)
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
/* Copyright (C) 2010 The Android Open Source Project
**
** This software is licensed under the terms of the GNU General Public
** License version 2, as published by the Free Software Foundation, and
** may be copied, distributed, and modified under those terms.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
*/

#include <unistd.h>

#include "sockets.h"
#include "qemu-common.h"
#include "errno.h"
#include "iolooper.h"
#include "android/android.h"
#include "android/utils/debug.h"
#include "android/globals.h"
#include "android/utils/system.h"
#include "android/protocol/core-connection.h"

/* Descriptor for a client, connected to the core via console port. */
struct CoreConnection {
    /* Socket address of the console. */
    SockAddress console_address;

    // Helper for performing sync I/O on the console socket.
    SyncSocket* ssocket;

    /* Stream name. Can be:
     *  - NULL for the console itself.
     *  - "attach-UI" for the attached UI client.
     */
    char* stream_name;
};

/*
 * Zero-terminates string buffer.
 * Param:
 *  buf - Buffer containing the string.
 *  buf_size - Buffer size.
 *  eos - String size.
 */
static inline void
_zero_terminate(char* buf, size_t buf_size, size_t eos)
{
    if (eos < buf_size) {
        buf[eos] = '\0';
    } else {
        buf[buf_size - 1] = '\0';
    }
}

/*
 * Checks if console has replied with "OK"
 * Param:
 *  reply - String containing console's reply
 * Return:
 *  boolean: true if reply was "OK", or false otherwise.
 */
static int
_is_reply_ok(const char* reply, int reply_size)
{
    return (reply_size < 2) ? 0 : (reply[0] == 'O' && reply[1] == 'K');
}

/*
 * Checks if console has replied with "KO"
 * Param:
 *  reply - String containing console's reply
 * Return:
 *  boolean: true if reply was "KO", or false otherwise.
 */
static int
_is_reply_ko(const char* reply, int reply_size)
{
    return (reply_size < 2) ? 0 : (reply[0] == 'K' && reply[1] == 'O');
}

SyncSocket*
core_connection_open_socket(SockAddress* sockaddr)
{
    SyncSocket* ssocket;
    int status;
    int64_t deadline;
    char buf[512];

    int fd = socket_create(sock_address_get_family(sockaddr), SOCKET_STREAM);
    if (fd < 0) {
        return NULL;
    }

    socket_set_xreuseaddr(fd);

    // Create sync connection to the console.
    ssocket = syncsocket_connect(fd, sockaddr, CORE_PORT_TIMEOUT_MS);
    if (ssocket == NULL) {
        derror("syncsocket_connect has failed: %s\n", errno_str);
        socket_close(fd);
        return NULL;
    }

    // Upon successful connection the console will reply with two strings:
    // "Android Console....", and "OK\r\n". Read them and check.
    status = syncsocket_start_read(ssocket);
    if (status < 0) {
        derror("syncsocket_start_read has failed: %s\n", errno_str);
        syncsocket_free(ssocket);
        return NULL;
    }

    deadline = iolooper_now() + CORE_PORT_TIMEOUT_MS;
    // Read first line.
    status = syncsocket_read_line_absolute(ssocket, buf, sizeof(buf), deadline);
    if (status <= 0) {
        derror("syncsocket_read_line_absolute has failed: %s\n", errno_str);
        syncsocket_free(ssocket);
        return NULL;
    }
    if (status < 15 || memcmp(buf, "Android Console", 15)) {
        _zero_terminate(buf, sizeof(buf), status);
        derror("console has failed the connection: %s\n", buf);
        syncsocket_free(ssocket);
        return NULL;
    }
    // Read second line
    status = syncsocket_read_line_absolute(ssocket, buf, sizeof(buf), deadline);
    syncsocket_stop_read(ssocket);
    if (status < 2 || !_is_reply_ok(buf, status)) {
        _zero_terminate(buf, sizeof(buf), status);
        derror("unexpected reply from the console: %s\n", buf);
        syncsocket_free(ssocket);
        return NULL;
    }

    return ssocket;
}

CoreConnection*
core_connection_create(SockAddress* console_address)
{
    CoreConnection* desc;
    ANEW0(desc);
    desc->console_address = console_address[0];
    desc->ssocket = NULL;
    desc->stream_name = NULL;

    return desc;
}

void
core_connection_free(CoreConnection* desc)
{
    if (desc == NULL) {
        return;
    }
    if (desc->ssocket != NULL) {
        syncsocket_free(desc->ssocket);
    }
    if (desc->stream_name != NULL) {
        free(desc->stream_name);
    }
    free(desc);
}

int
core_connection_open(CoreConnection* desc)
{
    if (desc == NULL) {
        errno = EINVAL;
        return -1;
    }
    if (desc->ssocket != NULL) {
        return 0;
    }

    desc->ssocket = core_connection_open_socket(&desc->console_address);

    return (desc->ssocket != NULL) ? 0 : -1;
}

void
core_connection_close(CoreConnection* desc)
{
    if (desc == NULL) {
        return;
    }
    if (desc->ssocket != NULL) {
        syncsocket_close(desc->ssocket);
    }
}

int
core_connection_write(CoreConnection* desc,
                      const void* buffer,
                      size_t to_write,
                      size_t* written_bytes)
{
    ssize_t written;

    int status = syncsocket_start_write(desc->ssocket);
    if (status < 0) {
        derror("syncsocket_start_write failed: %s\n", errno_str);
        return status;
    }

    written =
        syncsocket_write(desc->ssocket, buffer, to_write, CORE_PORT_TIMEOUT_MS);
    syncsocket_stop_write(desc->ssocket);
    if (written <= 0) {
        derror("syncsocket_write failed: %s\n", errno_str);
        return -1;
    }
    if (written_bytes != NULL) {
        *written_bytes = written;
    }

    return 0;
}

int
core_connection_read(CoreConnection* desc,
                     void* buffer,
                     size_t to_read,
                     size_t* read_bytes)
{
    ssize_t read_size;

    int status = syncsocket_start_read(desc->ssocket);
    if (status < 0) {
        derror("syncsocket_start_read failed: %s\n", errno_str);
        return status;
    }

    read_size =
        syncsocket_read(desc->ssocket, buffer, to_read, CORE_PORT_TIMEOUT_MS);
    syncsocket_stop_read(desc->ssocket);
    if (read_size <= 0) {
        derror("syncsocket_read failed: %s\n", errno_str);
        return -1;
    }

    if (read_bytes != NULL) {
        *read_bytes = read_size;
    }
    return 0;
}

int
core_connection_switch_stream(CoreConnection* desc,
                              const char* stream_name,
                              char** handshake)
{
    char buf[4096];
    int handshake_len;
    int status;
    int64_t deadline;

    *handshake = NULL;
    if (desc == NULL || desc->stream_name != NULL || stream_name == NULL) {
        errno = EINVAL;
        return -1;
    }

    // Prepare and write "switch" command.
    snprintf(buf, sizeof(buf), "qemu %s\r\n", stream_name);
    if (core_connection_write(desc, buf, strlen(buf), NULL)) {
        return -1;
    }

    // Read result / handshake
    status = syncsocket_start_read(desc->ssocket);
    if (status < 0) {
        return -1;
    }
    deadline = iolooper_now() + CORE_PORT_TIMEOUT_MS;
    handshake_len =
        syncsocket_read_line_absolute(desc->ssocket, buf, sizeof(buf), deadline);
    _zero_terminate(buf, sizeof(buf), handshake_len);
    // Replace terminating "\r\n" with 0
    if (handshake_len >= 1) {
        if (buf[handshake_len - 1] == '\r' || buf[handshake_len - 1] == '\n') {
            buf[handshake_len - 1] = '\0';
            if (handshake_len >= 2 && (buf[handshake_len - 2] == '\r' ||
                                       buf[handshake_len - 2] == '\n')) {
                buf[handshake_len - 2] = '\0';
            }
        }
    }
    // Lets see what kind of response we've got here.
    if (_is_reply_ok(buf, handshake_len)) {
        *handshake = strdup(buf + 3);
        desc->stream_name = strdup(stream_name);
        // We expect an "OK" string here
        status = syncsocket_read_line_absolute(desc->ssocket, buf, sizeof(buf),
                                               deadline);
        syncsocket_stop_read(desc->ssocket);
        if (status < 0) {
            derror("error reading console reply on stream switch: %s\n", errno_str);
            return -1;
        } else if (!_is_reply_ok(buf, status)) {
            _zero_terminate(buf, sizeof(buf), status);
            derror("unexpected console reply when switching streams: %s\n", buf);
            return -1;
        }
        return 0;
    } else if (_is_reply_ko(buf, handshake_len)) {
        derror("console has rejected stream switch: %s\n", buf);
        syncsocket_stop_read(desc->ssocket);
        *handshake = strdup(buf + 3);
        return -1;
    } else {
        // No OK, no KO? Should be an error!
        derror("unexpected console reply when switching streams: %s\n", buf);
        syncsocket_stop_read(desc->ssocket);
        *handshake = strdup(buf);
        return -1;
    }
}

CoreConnection*
core_connection_create_and_switch(SockAddress* console_socket,
                                  const char* stream_name,
                                  char** handshake)
{
    char switch_cmd[256];
    CoreConnection* connection = NULL;

    // Connect to the console service.
    connection = core_connection_create(console_socket);
    if (connection == NULL) {
        return NULL;
    }
    if (core_connection_open(connection)) {
        core_connection_free(connection);
        return NULL;
    }

    // Perform the switch.
    snprintf(switch_cmd, sizeof(switch_cmd), "%s", stream_name);
    if (core_connection_switch_stream(connection, switch_cmd, handshake)) {
        core_connection_close(connection);
        core_connection_free(connection);
        return NULL;
    }

    return connection;
}

void
core_connection_detach(CoreConnection* desc)
{
    core_connection_write(desc, "\n", 1, NULL);
}

int
core_connection_get_socket(CoreConnection* desc)
{
    return (desc != NULL) ? syncsocket_get_socket(desc->ssocket) : -1;
}