aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmi-firmware-update/qfu-udev-helpers.c
blob: 3412f46512a60afaa9b3889c2eb0e5fbe683d4bc (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
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
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * qmi-firmware-update -- Command line tool to update firmware in QMI 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 "config.h"

#include <stdlib.h>

#include <gio/gio.h>

#if defined WITH_UDEV
# include <gudev/gudev.h>
#endif

#include "qfu-udev-helpers.h"

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

static const gchar *device_type_str[] = {
    [QFU_UDEV_HELPER_DEVICE_TYPE_TTY]     = "tty",
    [QFU_UDEV_HELPER_DEVICE_TYPE_CDC_WDM] = "cdc-wdm",
};

G_STATIC_ASSERT (G_N_ELEMENTS (device_type_str) == QFU_UDEV_HELPER_DEVICE_TYPE_LAST);

const gchar *
qfu_udev_helper_device_type_to_string (QfuUdevHelperDeviceType type)
{
    return device_type_str[type];
}

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

#if defined WITH_UDEV

static const gchar *tty_subsys_list[]     = { "tty", NULL };
static const gchar *cdc_wdm_subsys_list[] = { "usbmisc", "usb", NULL };

static gboolean
udev_helper_get_udev_device_details (GUdevDevice  *device,
                                     gchar       **out_sysfs_path,
                                     guint16      *out_vid,
                                     guint16      *out_pid,
                                     guint        *out_busnum,
                                     guint        *out_devnum,
                                     GError      **error)
{
    GUdevDevice *parent;
    gulong       aux;

    if (out_vid)
        *out_vid = 0;
    if (out_pid)
        *out_pid = 0;
    if (out_sysfs_path)
        *out_sysfs_path = NULL;
    if (out_busnum)
        *out_busnum = 0;
    if (out_devnum)
        *out_devnum = 0;

    /* We need to look for the parent GUdevDevice which has a "usb_device"
     * devtype. */

    parent = g_udev_device_get_parent (device);
    while (parent) {
        GUdevDevice *next;

        if (g_strcmp0 (g_udev_device_get_devtype (parent), "usb_device") == 0)
            break;

        /* Check next parent */
        next = g_udev_device_get_parent (parent);
        g_object_unref (parent);
        parent = next;
    }

    if (!parent) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "couldn't find parent physical USB device");
        return FALSE;
    }

    if (out_sysfs_path)
        *out_sysfs_path = g_strdup (g_udev_device_get_sysfs_path (parent));

    if (out_vid) {
        aux = strtoul (g_udev_device_get_property (parent, "ID_VENDOR_ID"), NULL, 16);
        if (aux <= G_MAXUINT16)
            *out_vid = (guint16) aux;
    }

    if (out_pid) {
        aux = strtoul (g_udev_device_get_property (parent, "ID_MODEL_ID"), NULL, 16);
        if (aux <= G_MAXUINT16)
            *out_pid = (guint16) aux;
    }

    if (out_busnum) {
        aux = strtoul (g_udev_device_get_property (parent, "BUSNUM"), NULL, 10);
        if (aux <= G_MAXUINT)
            *out_busnum = (guint16) aux;
    }

    if (out_devnum) {
        aux = strtoul (g_udev_device_get_property (parent, "DEVNUM"), NULL, 10);
        if (aux <= G_MAXUINT)
            *out_devnum = (guint16) aux;
    }

    g_object_unref (parent);
    return TRUE;
}

static gboolean
udev_helper_get_udev_interface_details (GUdevDevice  *device,
                                        gchar       **out_driver,
                                        GError      **error)
{
    GUdevDevice *parent;

    /* We need to look for the parent GUdevDevice which has a "usb_interface"
     * devtype. */

    parent = g_udev_device_get_parent (device);
    while (parent) {
        GUdevDevice *next;

        if (g_strcmp0 (g_udev_device_get_devtype (parent), "usb_interface") == 0)
            break;

        /* Check next parent */
        next = g_udev_device_get_parent (parent);
        g_object_unref (parent);
        parent = next;
    }

    if (!parent) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "couldn't find parent interface USB device");
        return FALSE;
    }

    if (out_driver)
        *out_driver = g_strdup (g_udev_device_get_driver (parent));

    g_object_unref (parent);
    return TRUE;
}

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

gchar *
qfu_udev_helper_find_by_file (GFile   *file,
                              GError **error)
{
    GUdevClient  *client = NULL;
    GUdevDevice  *device = NULL;
    gchar        *basename = NULL;
    const gchar **subsys_list = NULL;
    gchar        *sysfs_path = NULL;
    guint         i;

    basename = g_file_get_basename (file);
    if (!basename) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "couldn't get filename");
        goto out;
    }

    client = g_udev_client_new (NULL);

    if (g_str_has_prefix (basename, "tty"))
        subsys_list = tty_subsys_list;
    else if  (g_str_has_prefix (basename, "cdc-wdm"))
        subsys_list = cdc_wdm_subsys_list;
    else {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "unknown device file type");
        goto out;
    }

    for (i = 0; !device && subsys_list[i]; i++)
        device = g_udev_client_query_by_subsystem_and_name (client, subsys_list[i], basename);

    if (!device) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "device not found");
        goto out;
    }

    if (!udev_helper_get_udev_device_details (device,
                                              &sysfs_path, NULL, NULL, NULL, NULL,
                                              error))
        goto out;

    g_debug ("[qfu-udev] sysfs path for '%s' found: %s", basename, sysfs_path);

out:
    g_free (basename);
    g_clear_object (&device);
    g_clear_object (&client);
    return sysfs_path;
}

gchar *
qfu_udev_helper_find_by_file_path (const gchar  *path,
                                   GError      **error)
{
    GFile *file;
    gchar *sysfs_path;

    file = g_file_new_for_path (path);
    sysfs_path = qfu_udev_helper_find_by_file (file, error);
    g_object_unref (file);
    return sysfs_path;
}

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

static gboolean
udev_helper_device_already_added (GPtrArray   *ptr,
                                  const gchar *sysfs_path)
{
    guint i;

    for (i = 0; i < ptr->len; i++) {
        if (g_strcmp0 (g_ptr_array_index (ptr, i), sysfs_path) == 0)
            return TRUE;
    }

    return FALSE;
}

static GPtrArray *
udev_helper_find_by_device_info_in_subsystem (GPtrArray    *sysfs_paths,
                                              GUdevClient  *udev,
                                              const gchar  *subsystem,
                                              guint16       vid,
                                              guint16       pid,
                                              guint         busnum,
                                              guint         devnum)
{
    GList     *devices;
    GList     *iter;

    devices = g_udev_client_query_by_subsystem (udev, subsystem);
    for (iter = devices; iter; iter = g_list_next (iter)) {
        GUdevDevice *device;
        guint16      device_vid = 0;
        guint16      device_pid = 0;
        guint        device_busnum = 0;
        guint        device_devnum = 0;
        gchar       *device_sysfs_path = NULL;

        device = G_UDEV_DEVICE (iter->data);

        if (udev_helper_get_udev_device_details (device,
                                                 &device_sysfs_path,
                                                 &device_vid,
                                                 &device_pid,
                                                 &device_busnum,
                                                 &device_devnum,
                                                 NULL)) {
            if ((vid == 0 || vid == device_vid) &&
                (pid == 0 || pid == device_pid) &&
                (busnum == 0 || busnum == device_busnum) &&
                (devnum == 0 || devnum == device_devnum) &&
                (!udev_helper_device_already_added (sysfs_paths, device_sysfs_path)))
                g_ptr_array_add (sysfs_paths, device_sysfs_path);
            else
                g_free (device_sysfs_path);
        }

        g_object_unref (device);
    }
    g_list_free (devices);
    return sysfs_paths;
}

gchar *
qfu_udev_helper_find_by_device_info (guint16   vid,
                                     guint16   pid,
                                     guint     busnum,
                                     guint     devnum,
                                     GError  **error)
{
    GUdevClient *udev;
    guint        i;
    GPtrArray   *sysfs_paths;
    GString     *match_str;
    gchar       *sysfs_path = NULL;

    sysfs_paths = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);
    udev        = g_udev_client_new (NULL);
    match_str   = g_string_new ("");

    if (vid != 0)
        g_string_append_printf (match_str, "vid 0x%04x", vid);
    if (pid != 0)
        g_string_append_printf (match_str, "%spid 0x%04x", match_str->len > 0 ? ", " : "", pid);
    if (busnum != 0)
        g_string_append_printf (match_str, "%sbus %03u", match_str->len > 0 ? ", " : "", busnum);
    if (devnum != 0)
        g_string_append_printf (match_str, "%sdev %03u", match_str->len > 0 ? ", " : "", devnum);
    g_assert (match_str->len > 0);

    for (i = 0; tty_subsys_list[i]; i++)
        sysfs_paths = udev_helper_find_by_device_info_in_subsystem (sysfs_paths,
                                                                    udev,
                                                                    tty_subsys_list[i],
                                                                    vid, pid, busnum, devnum);

    for (i = 0; cdc_wdm_subsys_list[i]; i++)
        sysfs_paths = udev_helper_find_by_device_info_in_subsystem (sysfs_paths,
                                                                    udev,
                                                                    cdc_wdm_subsys_list[i],
                                                                    vid, pid, busnum, devnum);

    for (i = 0; i < sysfs_paths->len; i++)
        g_debug ("[%s] sysfs path: %s", match_str->str, (gchar *) g_ptr_array_index (sysfs_paths, i));

    if (sysfs_paths->len == 0) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "no device found with matching criteria: %s",
                     match_str->str);
        goto out;
    }

    if (sysfs_paths->len > 1) {
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                     "multiple devices (%u) found with matching criteria: %s",
                     sysfs_paths->len, match_str->str);
        goto out;
    }

    sysfs_path = g_strdup (g_ptr_array_index (sysfs_paths, 0));

out:

    g_ptr_array_unref (sysfs_paths);
    g_string_free (match_str, TRUE);
    g_object_unref (udev);

    return sysfs_path;
}

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

static GFile *
device_matches_sysfs_and_type (GUdevDevice             *device,
                               const gchar             *sysfs_path,
                               QfuUdevHelperDeviceType  type)
{
    GFile *file = NULL;
    gchar *device_sysfs_path = NULL;
    gchar *device_driver = NULL;
    gchar *device_path = NULL;

    if (!udev_helper_get_udev_device_details (device,
                                              &device_sysfs_path, NULL, NULL, NULL, NULL,
                                              NULL))
        goto out;

    if (!device_sysfs_path)
        goto out;

    if (g_strcmp0 (device_sysfs_path, sysfs_path) != 0)
        goto out;

    if (!udev_helper_get_udev_interface_details (device,
                                                 &device_driver,
                                                 NULL))
        goto out;

    switch (type) {
    case QFU_UDEV_HELPER_DEVICE_TYPE_TTY:
        if (g_strcmp0 (device_driver, "qcserial") != 0)
            goto out;
        break;
    case QFU_UDEV_HELPER_DEVICE_TYPE_CDC_WDM:
        if (g_strcmp0 (device_driver, "qmi_wwan") != 0 && g_strcmp0 (device_driver, "cdc_mbim") != 0)
            goto out;
        break;
    default:
        g_assert_not_reached ();
    }

    device_path = g_strdup_printf ("/dev/%s", g_udev_device_get_name (device));
    file = g_file_new_for_path (device_path);
    g_free (device_path);

out:
    g_free (device_sysfs_path);
    g_free (device_driver);
    return file;
}

GList *
qfu_udev_helper_list_devices (QfuUdevHelperDeviceType  device_type,
                              const gchar             *sysfs_path)
{
    GUdevClient  *udev;
    const gchar **subsys_list = NULL;
    guint         i;
    GList        *files = NULL;

    udev = g_udev_client_new (NULL);

    switch (device_type) {
    case QFU_UDEV_HELPER_DEVICE_TYPE_TTY:
        subsys_list = tty_subsys_list;
        break;
    case QFU_UDEV_HELPER_DEVICE_TYPE_CDC_WDM:
        subsys_list = cdc_wdm_subsys_list;
        break;
    default:
        g_assert_not_reached ();
    }

    for (i = 0; subsys_list[i]; i++) {
        GList *devices, *iter;

        devices = g_udev_client_query_by_subsystem (udev, subsys_list[i]);
        for (iter = devices; iter; iter = g_list_next (iter)) {
            GFile *file;

            file = device_matches_sysfs_and_type (G_UDEV_DEVICE (iter->data), sysfs_path, device_type);
            if (file)
                files = g_list_prepend (files, file);
            g_object_unref (G_OBJECT (iter->data));
        }
        g_list_free (devices);
    }

    g_object_unref (udev);
    return files;
}

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

#define WAIT_FOR_DEVICE_TIMEOUT_SECS 120

typedef struct {
    QfuUdevHelperDeviceType  device_type;
    GUdevClient             *udev;
    gchar                   *sysfs_path;
    guint                    timeout_id;
    gulong                   uevent_id;
    gulong                   cancellable_id;
} WaitForDeviceContext;

static void
wait_for_device_context_free (WaitForDeviceContext *ctx)
{
    g_assert (!ctx->timeout_id);
    g_assert (!ctx->uevent_id);
    g_assert (!ctx->cancellable_id);

    g_object_unref (ctx->udev);
    g_free (ctx->sysfs_path);
    g_slice_free (WaitForDeviceContext, ctx);
}

GFile *
qfu_udev_helper_wait_for_device_finish (GAsyncResult  *res,
                                        GError       **error)
{
    return G_FILE (g_task_propagate_pointer (G_TASK (res), error));
}

static void
handle_uevent (GUdevClient *client,
               const char  *action,
               GUdevDevice *device,
               GTask       *task)
{
    WaitForDeviceContext *ctx;
    GFile                *file;

    ctx = (WaitForDeviceContext *) g_task_get_task_data (task);

    if (!g_str_equal (action, "add") && !g_str_equal (action, "move") && !g_str_equal (action, "change"))
        return;

    file = device_matches_sysfs_and_type (device, ctx->sysfs_path, ctx->device_type);
    if (!file)
        return;

    g_debug ("[qfu-udev] waiting device (%s) matched: %s",
             qfu_udev_helper_device_type_to_string (ctx->device_type),
             g_udev_device_get_name (device));

    /* Disconnect this handler */
    g_signal_handler_disconnect (ctx->udev, ctx->uevent_id);
    ctx->uevent_id = 0;

    /* Disconnect the other handlers */
    g_cancellable_disconnect (g_task_get_cancellable (task), ctx->cancellable_id);
    ctx->cancellable_id = 0;
    g_source_remove (ctx->timeout_id);
    ctx->timeout_id = 0;

    g_task_return_pointer (task, file, g_object_unref);
    g_object_unref (task);
}

static gboolean
wait_for_device_timed_out (GTask *task)
{
    WaitForDeviceContext *ctx;

    ctx = (WaitForDeviceContext *) g_task_get_task_data (task);

    /* Disconnect this handler */
    ctx->timeout_id = 0;

    /* Disconnect the other handlers */
    g_cancellable_disconnect (g_task_get_cancellable (task), ctx->cancellable_id);
    ctx->cancellable_id = 0;
    g_signal_handler_disconnect (ctx->udev, ctx->uevent_id);
    ctx->uevent_id = 0;

    g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
                             "waiting for device at '%s' timed out",
                             ctx->sysfs_path);
    g_object_unref (task);
    return FALSE;
}

static void
wait_for_device_cancelled (GCancellable *cancellable,
                           GTask        *task)
{
    WaitForDeviceContext *ctx;

    ctx = (WaitForDeviceContext *) g_task_get_task_data (task);

    /* Disconnect this handler */
    g_cancellable_disconnect (g_task_get_cancellable (task), ctx->cancellable_id);
    ctx->cancellable_id = 0;

    /* Disconnect the other handlers */
    g_source_remove (ctx->timeout_id);
    ctx->timeout_id = 0;
    g_signal_handler_disconnect (ctx->udev, ctx->uevent_id);
    ctx->uevent_id = 0;

    g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_CANCELLED,
                             "waiting for device at '%s' cancelled",
                             ctx->sysfs_path);
    g_object_unref (task);
}

void
qfu_udev_helper_wait_for_device (QfuUdevHelperDeviceType  device_type,
                                 const gchar             *sysfs_path,
                                 GCancellable            *cancellable,
                                 GAsyncReadyCallback      callback,
                                 gpointer                 user_data)
{
    GTask                *task;
    WaitForDeviceContext *ctx;

    ctx = g_slice_new0 (WaitForDeviceContext);
    ctx->device_type = device_type;
    ctx->sysfs_path = g_strdup (sysfs_path);

    if (ctx->device_type == QFU_UDEV_HELPER_DEVICE_TYPE_TTY)
        ctx->udev = g_udev_client_new (tty_subsys_list);
    else if (ctx->device_type == QFU_UDEV_HELPER_DEVICE_TYPE_CDC_WDM)
        ctx->udev = g_udev_client_new (cdc_wdm_subsys_list);
    else
        g_assert_not_reached ();

    task = g_task_new (NULL, cancellable, callback, user_data);
    g_task_set_task_data (task, ctx, (GDestroyNotify) wait_for_device_context_free);

    /* Monitor for device additions. */
    ctx->uevent_id = g_signal_connect (ctx->udev,
                                       "uevent",
                                       G_CALLBACK (handle_uevent),
                                       task);

    /* Allow cancellation */
    ctx->cancellable_id = g_cancellable_connect (cancellable,
                                                 (GCallback) wait_for_device_cancelled,
                                                 task,
                                                 NULL);

    /* And also, setup a timeout to avoid waiting forever. */
    ctx->timeout_id = g_timeout_add_seconds (WAIT_FOR_DEVICE_TIMEOUT_SECS,
                                             (GSourceFunc) wait_for_device_timed_out,
                                             task);

    /* Note: task ownership is shared between the signals and the timeout */
}

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

struct _QfuUdevHelperGenericMonitor {
    GUdevClient *udev;
};

void
qfu_udev_helper_generic_monitor_free (QfuUdevHelperGenericMonitor *self)
{
    g_object_unref (self->udev);
    g_slice_free (QfuUdevHelperGenericMonitor, self);
}

static void
handle_uevent_generic (GUdevClient *client,
                       const char  *action,
                       GUdevDevice *device,
                       GTask       *task)
{
    g_debug ("[qfu-udev] event: %s %s", action, g_udev_device_get_name (device));
}

QfuUdevHelperGenericMonitor *
qfu_udev_helper_generic_monitor_new (const gchar *sysfs_path)
{
    static const gchar *all_list[] = {
        "usbmisc", "usb",
        "tty",
        "net",
        NULL };

    QfuUdevHelperGenericMonitor *self;

    self = g_slice_new0 (QfuUdevHelperGenericMonitor);
    self->udev = g_udev_client_new (all_list);

    /* Monitor for device events. */
    g_signal_connect (self->udev, "uevent", G_CALLBACK (handle_uevent_generic), NULL);
    return self;
}

#endif /* WITH_UDEV */