aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmi-firmware-update/qfu-at-device.c
blob: a6604a30a9da73469fa84899ffd5e26771dbef1e (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
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
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Qfu-firmware-update -- Command line tool to update firmware in QFU devices
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright (C) 2016 Zodiac Inflight Innovations
 * Copyright (C) 2016-2017 Aleksander Morgado <aleksander@aleksander.es>
 */

#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>

#include <glib-object.h>
#include <gio/gio.h>

#include <libqmi-glib.h>

#include "qfu-log.h"
#include "qfu-at-device.h"
#include "qfu-utils.h"

#define QFU_AT_BUFFER_SIZE 128

static void initable_iface_init (GInitableIface *iface);

G_DEFINE_TYPE_EXTENDED (QfuAtDevice, qfu_at_device, G_TYPE_OBJECT, 0,
                        G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init))

enum {
    PROP_0,
    PROP_FILE,
    PROP_LAST
};

static GParamSpec *properties[PROP_LAST];

struct _QfuAtDevicePrivate {
    GFile      *file;
    gchar      *name;
    gint        fd;
    GByteArray *buffer;
};

/******************************************************************************/
/* Send */

static gboolean
send_request (QfuAtDevice   *self,
              const gchar   *request,
              GCancellable  *cancellable,
              GError       **error)
{
    gssize         wlen;
    fd_set         wr;
    gint           aux;
    struct timeval tv = {
        .tv_sec = 2,
        .tv_usec = 0,
    };

    /* Wait for the fd to be writable and don't wait forever */
    FD_ZERO (&wr);
    FD_SET (self->priv->fd, &wr);
    aux = select (self->priv->fd + 1, NULL, &wr, NULL, &tv);

    if (g_cancellable_set_error_if_cancelled (cancellable, error))
        return FALSE;

    if (aux < 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "error waiting to write: %s",
                     g_strerror (errno));
        return FALSE;
    }

    if (aux == 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "timed out waiting to write");
        return FALSE;
    }

    /* Debug output */
    if (qfu_log_get_verbose ())
        g_debug ("[qfu-at-device,%s] >> %s", self->priv->name, request);

    wlen = write (self->priv->fd, request, strlen (request));
    if (wlen < 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "error writting: %s",
                     g_strerror (errno));
        return FALSE;
    }

    /* We treat EINTR as an error, so we also treat as an error if not all bytes
     * were wlen */
    if (wlen != strlen (request)) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "error writing: only %" G_GSSIZE_FORMAT "/%" G_GSIZE_FORMAT " bytes written",
                     wlen, wlen);
        return FALSE;
    }

    wlen = write (self->priv->fd, "\r", 1);
    if (wlen < 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "error writting <CR>: %s",
                     g_strerror (errno));
        return FALSE;
    }

    return TRUE;
}

/******************************************************************************/
/* Receive */

static gssize
receive_response (QfuAtDevice   *self,
                  guint          timeout_secs,
                  gchar        **response,
                  GCancellable  *cancellable,
                  GError       **error)
{
	fd_set          rd;
	struct timeval  tv;
    gint            aux;
    gssize          rlen;
    gchar          *start;

    /* Use requested timeout */
    tv.tv_sec  = timeout_secs;
    tv.tv_usec = 0;

	FD_ZERO (&rd);
	FD_SET (self->priv->fd, &rd);
    aux = select (self->priv->fd + 1, &rd, NULL, NULL, &tv);

    if (g_cancellable_set_error_if_cancelled (cancellable, error))
        return -1;

    if (aux < 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "error waiting to read response: %s",
                     g_strerror (errno));
        return -1;
    }

    if (aux == 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "timed out waiting for the response");
        return -1;
    }

    /* Receive in the primary buffer */
	rlen = read (self->priv->fd, self->priv->buffer->data, self->priv->buffer->len);
	if (rlen < 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "couldn't read response: %s",
                     g_strerror (errno));
        return -1;
    }

    if (rlen == 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "couldn't read response: HUP detected");
        return -1;
    }

    /* Force end of string */
    start = (gchar *) &self->priv->buffer->data[0];
    start[rlen] = '\0';

    /* Remove trailing LFs and CRs */
    while (rlen > 0 && (start[rlen - 1] == '\r' || start[rlen - 1] == '\n'))
        start[--rlen] = '\0';

    /* Remove heading LFs and CRs */
    while (rlen > 0 && (start[0] == '\r' || start[0] == '\n')) {
        start++;
        rlen--;
    }

    /* Debug output */
    if (qfu_log_get_verbose ())
        g_debug ("[qfu-at-device,%s] << %s", self->priv->name, start);

    if (response)
        *response = start;

    return rlen;
}

/******************************************************************************/
/* Send/receive */

static gssize
send_receive (QfuAtDevice   *self,
              const gchar   *request,
              guint          response_timeout_secs,
              gchar        **response,
              GCancellable  *cancellable,
              GError       **error)
{
    gboolean sent;

    if (self->priv->fd < 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "device is closed");
        return FALSE;
    }

    sent = send_request (self, request, cancellable, error);
    if (!sent)
        return -1;

    if (!response)
        return 0;

    while (1) {
        gssize rsplen;

        rsplen = receive_response (self, response_timeout_secs, response, cancellable, error);
        if (rsplen > 0 && g_str_has_prefix (*response, request)) {
            *response += strlen (request);
            rsplen -= strlen (request);
            if (rsplen == 0)
                continue;
        }

        return rsplen;
    }
}

/******************************************************************************/

gboolean
qfu_at_device_boothold (QfuAtDevice  *self,
                        GCancellable  *cancellable,
                        GError       **error)
{
    gssize  rsplen;
    gchar  *rsp = NULL;

    rsplen = send_receive (self, "AT!BOOTHOLD", 3, &rsp, cancellable, error);
    if (rsplen < 0)
        return FALSE;

    if (strstr (rsp, "OK"))
        return TRUE;

    if (strstr (rsp, "ERROR"))
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "unknown command");
    else
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "unknown error");
    return FALSE;
}

/******************************************************************************/

static gboolean
initable_init (GInitable     *initable,
               GCancellable  *cancellable,
               GError       **error)
{
    QfuAtDevice    *self;
    struct termios  terminal_data;
    gchar          *path = NULL;
    GError         *inner_error = NULL;

    self = QFU_AT_DEVICE (initable);

    if (g_cancellable_set_error_if_cancelled (cancellable, &inner_error))
        goto out;

    path = g_file_get_path (self->priv->file);
    g_debug ("[qfu-at-device,%s] opening TTY", self->priv->name);

    self->priv->fd = open (path, O_RDWR | O_NOCTTY);
    if (self->priv->fd < 0) {
        inner_error = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "error opening serial device: %s",
                                   g_strerror (errno));
        goto out;
    }

    g_debug ("[qfu-at-device,%s] setting up serial port...", self->priv->name);
    if (tcgetattr (self->priv->fd, &terminal_data) < 0) {
        inner_error = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "error getting serial port attributes: %s",
                                   g_strerror (errno));
        goto out;
    }

    terminal_data.c_iflag &= ~(IGNCR | ICRNL | IUCLC | INPCK | IXON | IXANY );
    terminal_data.c_oflag &= ~(OPOST | OLCUC | OCRNL | ONLCR | ONLRET);
    terminal_data.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHONL);
    terminal_data.c_cc[VMIN] = 1;
    terminal_data.c_cc[VTIME] = 0;
    terminal_data.c_cc[VEOF] = 1;
    terminal_data.c_iflag |= (IXON | IXOFF | IXANY | IGNPAR);
    terminal_data.c_cflag &= ~(CBAUD | CSIZE | CSTOPB | PARENB | CRTSCTS);
    terminal_data.c_cflag |= (CS8 | CREAD | CLOCAL); /* 8N1 */

    errno = 0;
    if (cfsetispeed (&terminal_data, B115200) != 0) {
        inner_error = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "failed to set serial port input speed: %s",
                                   g_strerror (errno));
        goto out;
    }

    errno = 0;
    if (cfsetospeed (&terminal_data, B115200) != 0) {
        inner_error = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "failed to set serial port output speed: %s",
                                   g_strerror (errno));
        goto out;
    }

    if (tcsetattr (self->priv->fd, TCSANOW, &terminal_data) < 0) {
        inner_error = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "error setting serial port attributes: %s",
                                   g_strerror (errno));
        goto out;
    }

out:
    g_free (path);

    if (inner_error) {
        if (!(self->priv->fd < 0)) {
            close (self->priv->fd);
            self->priv->fd = -1;
        }
        g_propagate_error (error, inner_error);
        return FALSE;
    }

    return TRUE;
}

/******************************************************************************/

const gchar *
qfu_at_device_get_name (QfuAtDevice *self)
{
    return self->priv->name;
}

/******************************************************************************/

QfuAtDevice *
qfu_at_device_new (GFile         *file,
                   GCancellable  *cancellable,
                   GError       **error)
{
    g_return_val_if_fail (G_IS_FILE (file), NULL);

    return QFU_AT_DEVICE (g_initable_new (QFU_TYPE_AT_DEVICE,
                                           cancellable,
                                           error,
                                           "file", file,
                                           NULL));
}


static void
qfu_at_device_init (QfuAtDevice *self)
{
    self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, QFU_TYPE_AT_DEVICE, QfuAtDevicePrivate);
    self->priv->fd = -1;
    /* Long buffer for I/O */
    self->priv->buffer = g_byte_array_new ();
    g_byte_array_set_size (self->priv->buffer, QFU_AT_BUFFER_SIZE);
}

static void
set_property (GObject      *object,
              guint         prop_id,
              const GValue *value,
              GParamSpec   *pspec)
{
    QfuAtDevice *self = QFU_AT_DEVICE (object);

    switch (prop_id) {
    case PROP_FILE:
        self->priv->file = g_value_dup_object (value);
        if (self->priv->file)
            self->priv->name = g_file_get_basename (self->priv->file);
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
        break;
    }
}

static void
get_property (GObject    *object,
              guint       prop_id,
              GValue     *value,
              GParamSpec *pspec)
{
    QfuAtDevice *self = QFU_AT_DEVICE (object);

    switch (prop_id) {
    case PROP_FILE:
        g_value_set_object (value, self->priv->file);
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
        break;
    }
}

static void
dispose (GObject *object)
{
    QfuAtDevice *self = QFU_AT_DEVICE (object);

    if (!(self->priv->fd < 0)) {
        close (self->priv->fd);
        self->priv->fd = -1;
    }
    g_clear_pointer (&self->priv->name,   g_free);
    g_clear_pointer (&self->priv->buffer, g_byte_array_unref);
    g_clear_object  (&self->priv->file);

    G_OBJECT_CLASS (qfu_at_device_parent_class)->dispose (object);
}

static void
initable_iface_init (GInitableIface *iface)
{
    iface->init = initable_init;
}

static void
qfu_at_device_class_init (QfuAtDeviceClass *klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS (klass);

    g_type_class_add_private (object_class, sizeof (QfuAtDevicePrivate));

    object_class->dispose      = dispose;
    object_class->get_property = get_property;
    object_class->set_property = set_property;

    properties[PROP_FILE] =
        g_param_spec_object ("file",
                             "File",
                             "File object",
                             G_TYPE_FILE,
                             G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY);
    g_object_class_install_property (object_class, PROP_FILE, properties[PROP_FILE]);
}