Debian Codegraph @

src/libqmi-glib/qmi-helpers.c

raw
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3 /*
4 * libqmi-glib -- GLib/GIO based library to control QMI devices
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301 USA.
20 *
21 * Copyright (C) 2012-2020 Dan Williams <[email protected]>
22 * Copyright (C) 2012-2020 Aleksander Morgado <[email protected]>
23 */
24
25 #include <config.h>
26
27 #define _GNU_SOURCE
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <grp.h>
33 #include <pwd.h>
34 #include <errno.h>
35
36 #include "qmi-helpers.h"
37 #include "qmi-error-types.h"
38
39 /*****************************************************************************/
40
41 gboolean
42 qmi_helpers_check_user_allowed (uid_t uid,
43 GError **error)
44 {
45 #ifndef QMI_USERNAME_ENABLED
46 if (uid == 0)
47 return TRUE;
48 #else
49 # ifndef QMI_USERNAME
50 # error QMI username not defined
51 # endif
52
53 struct passwd *expected_usr = NULL;
54
55 /* Root user is always allowed, regardless of the specified QMI_USERNAME */
56 if (uid == 0)
57 return TRUE;
58
59 expected_usr = getpwnam (QMI_USERNAME);
60 if (!expected_usr) {
61 g_set_error (error,
62 G_IO_ERROR,
63 g_io_error_from_errno (errno),
64 "Not enough privileges (unknown username %s)", QMI_USERNAME);
65 return FALSE;
66 }
67
68 if (uid == expected_usr->pw_uid)
69 return TRUE;
70 #endif
71
72 g_set_error (error,
73 QMI_CORE_ERROR,
74 QMI_CORE_ERROR_FAILED,
75 "Not enough privileges");
76 return FALSE;
77 }
78
79 /*****************************************************************************/
80
81 gboolean
82 qmi_helpers_check_group_allowed (uid_t uid,
83 GError **error)
84 {
85 #ifndef QMI_GROUPNAME_ENABLED
86 if (uid == 0)
87 return TRUE;
88 #else
89 # ifndef QMI_GROUPNAME
90 # error QMI groupname not defined
91 # endif
92
93 struct passwd *pw;
94 struct group *grp;
95 guint i;
96
97 grp = getgrnam (QMI_GROUPNAME);
98 if (!grp) {
99 g_set_error (error,
100 G_IO_ERROR,
101 g_io_error_from_errno (errno),
102 "Not enough privileges (unknown group %s)", QMI_GROUPNAME);
103 return FALSE;
104 }
105
106 pw = getpwuid (uid);
107 if (pw && pw->pw_gid == grp->gr_gid)
108 return TRUE;
109
110 if (pw && grp->gr_mem) {
111 for (i = 0; grp->gr_mem[i]; i++) {
112 if (g_strcmp0 (grp->gr_mem[i], pw->pw_name) == 0)
113 return TRUE;
114 }
115 }
116 #endif
117 g_set_error (error,
118 QMI_CORE_ERROR,
119 QMI_CORE_ERROR_FAILED,
120 "Not enough privileges");
121 return FALSE;
122 }
123
124 /*****************************************************************************/
125
126 gboolean
127 qmi_helpers_string_utf8_validate_printable (const guint8 *utf8,
128 gsize utf8_len)
129 {
130 const gchar *p;
131 const gchar *init;
132
133 g_assert (utf8);
134 g_assert (utf8_len);
135
136 /* Ignore all trailing NUL bytes, if any */
137 while ((utf8_len > 0) && (utf8[utf8_len - 1] == '\0'))
138 utf8_len--;
139
140 /* An empty string */
141 if (!utf8_len)
142 return TRUE;
143
144 /* First check if valid UTF-8 */
145 init = (const gchar *)utf8;
146 if (!g_utf8_validate (init, utf8_len, NULL))
147 return FALSE;
148
149 /* Then check if contents are printable. If one is not,
150 * check fails. */
151 for (p = init; (gsize)(p - init) < utf8_len; p = g_utf8_next_char (p)) {
152 gunichar unichar;
153
154 /* Explicitly allow CR and LF even if they're control characters, given
155 * that NMEA traces reported via QMI LOC indications seem to have these
156 * suffixed.
157 * Also, explicitly allow TAB as some manufacturers seem to include it
158 * e.g. in model info strings. */
159 if (*p == '\r' || *p == '\n' || *p == '\t')
160 continue;
161
162 unichar = g_utf8_get_char (p);
163 if (!g_unichar_isprint (unichar))
164 return FALSE;
165 }
166 return TRUE;
167 }
168
169 /*****************************************************************************/
170 /* GSM 03.38 encoding conversion stuff, imported from ModemManager */
171
172 #define GSM_DEF_ALPHABET_SIZE 128
173 #define GSM_EXT_ALPHABET_SIZE 10
174
175 typedef struct GsmUtf8Mapping {
176 gchar chars[3];
177 guint8 len;
178 guint8 gsm; /* only used for extended GSM charset */
179 } GsmUtf8Mapping;
180
181 #define ONE(a) { {a, 0x00, 0x00}, 1, 0 }
182 #define TWO(a, b) { {a, b, 0x00}, 2, 0 }
183
184 /*
185 * Mapping from GSM default alphabet to UTF-8.
186 *
187 * ETSI GSM 03.38, version 6.0.1, section 6.2.1; Default alphabet. Mapping to UCS-2.
188 * Mapping according to http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
189 */
190 static const GsmUtf8Mapping gsm_def_utf8_alphabet[GSM_DEF_ALPHABET_SIZE] = {
191 /* @ £ $ ¥ */
192 ONE(0x40), TWO(0xc2, 0xa3), ONE(0x24), TWO(0xc2, 0xa5),
193 /* è é ù ì */
194 TWO(0xc3, 0xa8), TWO(0xc3, 0xa9), TWO(0xc3, 0xb9), TWO(0xc3, 0xac),
195 /* ò Ç \n Ø */
196 TWO(0xc3, 0xb2), TWO(0xc3, 0x87), ONE(0x0a), TWO(0xc3, 0x98),
197 /* ø \r Å å */
198 TWO(0xc3, 0xb8), ONE(0x0d), TWO(0xc3, 0x85), TWO(0xc3, 0xa5),
199 /* Δ _ Φ Γ */
200 TWO(0xce, 0x94), ONE(0x5f), TWO(0xce, 0xa6), TWO(0xce, 0x93),
201 /* Λ Ω Π Ψ */
202 TWO(0xce, 0x9b), TWO(0xce, 0xa9), TWO(0xce, 0xa0), TWO(0xce, 0xa8),
203 /* Σ Θ Ξ Escape Code */
204 TWO(0xce, 0xa3), TWO(0xce, 0x98), TWO(0xce, 0x9e), ONE(0xa0),
205 /* Æ æ ß É */
206 TWO(0xc3, 0x86), TWO(0xc3, 0xa6), TWO(0xc3, 0x9f), TWO(0xc3, 0x89),
207 /* ' ' ! " # */
208 ONE(0x20), ONE(0x21), ONE(0x22), ONE(0x23),
209 /* ¤ % & ' */
210 TWO(0xc2, 0xa4), ONE(0x25), ONE(0x26), ONE(0x27),
211 /* ( ) * + */
212 ONE(0x28), ONE(0x29), ONE(0x2a), ONE(0x2b),
213 /* , - . / */
214 ONE(0x2c), ONE(0x2d), ONE(0x2e), ONE(0x2f),
215 /* 0 1 2 3 */
216 ONE(0x30), ONE(0x31), ONE(0x32), ONE(0x33),
217 /* 4 5 6 7 */
218 ONE(0x34), ONE(0x35), ONE(0x36), ONE(0x37),
219 /* 8 9 : ; */
220 ONE(0x38), ONE(0x39), ONE(0x3a), ONE(0x3b),
221 /* < = > ? */
222 ONE(0x3c), ONE(0x3d), ONE(0x3e), ONE(0x3f),
223 /* ¡ A B C */
224 TWO(0xc2, 0xa1), ONE(0x41), ONE(0x42), ONE(0x43),
225 /* D E F G */
226 ONE(0x44), ONE(0x45), ONE(0x46), ONE(0x47),
227 /* H I J K */
228 ONE(0x48), ONE(0x49), ONE(0x4a), ONE(0x4b),
229 /* L M N O */
230 ONE(0x4c), ONE(0x4d), ONE(0x4e), ONE(0x4f),
231 /* P Q R S */
232 ONE(0x50), ONE(0x51), ONE(0x52), ONE(0x53),
233 /* T U V W */
234 ONE(0x54), ONE(0x55), ONE(0x56), ONE(0x57),
235 /* X Y Z Ä */
236 ONE(0x58), ONE(0x59), ONE(0x5a), TWO(0xc3, 0x84),
237 /* Ö Ñ Ü § */
238 TWO(0xc3, 0x96), TWO(0xc3, 0x91), TWO(0xc3, 0x9c), TWO(0xc2, 0xa7),
239 /* ¿ a b c */
240 TWO(0xc2, 0xbf), ONE(0x61), ONE(0x62), ONE(0x63),
241 /* d e f g */
242 ONE(0x64), ONE(0x65), ONE(0x66), ONE(0x67),
243 /* h i j k */
244 ONE(0x68), ONE(0x69), ONE(0x6a), ONE(0x6b),
245 /* l m n o */
246 ONE(0x6c), ONE(0x6d), ONE(0x6e), ONE(0x6f),
247 /* p q r s */
248 ONE(0x70), ONE(0x71), ONE(0x72), ONE(0x73),
249 /* t u v w */
250 ONE(0x74), ONE(0x75), ONE(0x76), ONE(0x77),
251 /* x y z ä */
252 ONE(0x78), ONE(0x79), ONE(0x7a), TWO(0xc3, 0xa4),
253 /* ö ñ ü à */
254 TWO(0xc3, 0xb6), TWO(0xc3, 0xb1), TWO(0xc3, 0xbc), TWO(0xc3, 0xa0)
255 };
256
257 static guint8
258 gsm_def_char_to_utf8 (const guint8 gsm,
259 guint8 *out_utf8)
260 {
261 if (gsm >= GSM_DEF_ALPHABET_SIZE)
262 return 0;
263 memcpy (out_utf8, &gsm_def_utf8_alphabet[gsm].chars[0], gsm_def_utf8_alphabet[gsm].len);
264 return gsm_def_utf8_alphabet[gsm].len;
265 }
266
267 #define EONE(a, g) { {a, 0x00, 0x00}, 1, g }
268 #define ETHR(a, b, c, g) { {a, b, c}, 3, g }
269
270 /* Mapping from GSM extended alphabet to UTF-8 */
271 static const GsmUtf8Mapping gsm_ext_utf8_alphabet[GSM_EXT_ALPHABET_SIZE] = {
272 /* form feed ^ { } */
273 EONE(0x0c, 0x0a), EONE(0x5e, 0x14), EONE(0x7b, 0x28), EONE(0x7d, 0x29),
274 /* \ [ ~ ] */
275 EONE(0x5c, 0x2f), EONE(0x5b, 0x3c), EONE(0x7e, 0x3d), EONE(0x5d, 0x3e),
276 /* | € */
277 EONE(0x7c, 0x40), ETHR(0xe2, 0x82, 0xac, 0x65)
278 };
279
280 #define GSM_ESCAPE_CHAR 0x1b
281
282 static guint8
283 gsm_ext_char_to_utf8 (const guint8 gsm,
284 guint8 *out_utf8)
285 {
286 int i;
287
288 for (i = 0; i < GSM_EXT_ALPHABET_SIZE; i++) {
289 if (gsm == gsm_ext_utf8_alphabet[i].gsm) {
290 memcpy (out_utf8, &gsm_ext_utf8_alphabet[i].chars[0], gsm_ext_utf8_alphabet[i].len);
291 return gsm_ext_utf8_alphabet[i].len;
292 }
293 }
294 return 0;
295 }
296
297 static guint8 *
298 charset_gsm_unpack (const guint8 *gsm,
299 guint32 num_septets,
300 guint8 start_offset, /* in _bits_ */
301 gsize *out_unpacked_len)
302 {
303 GByteArray *unpacked;
304 guint i;
305
306 unpacked = g_byte_array_sized_new (num_septets + 1);
307 for (i = 0; i < num_septets; i++) {
308 guint8 bits_here, bits_in_next, octet, offset, c;
309 guint32 start_bit;
310
311 start_bit = start_offset + (i * 7); /* Overall bit offset of char in buffer */
312 offset = start_bit % 8; /* Offset to start of char in this byte */
313 bits_here = offset ? (8 - offset) : 7;
314 bits_in_next = 7 - bits_here;
315
316 /* Grab bits in the current byte */
317 octet = gsm[start_bit / 8];
318 c = (octet >> offset) & (0xFF >> (8 - bits_here));
319
320 /* Grab any bits that spilled over to next byte */
321 if (bits_in_next) {
322 octet = gsm[(start_bit / 8) + 1];
323 c |= (octet & (0xFF >> (8 - bits_in_next))) << bits_here;
324 }
325 g_byte_array_append (unpacked, &c, 1);
326 }
327
328 *out_unpacked_len = unpacked->len;
329 return g_byte_array_free (unpacked, FALSE);
330 }
331
332 gchar *
333 qmi_helpers_string_utf8_from_gsm7 (const guint8 *gsm_packed,
334 gsize gsm_packed_len)
335 {
336 GByteArray *utf8;
337 guint8 *gsm_unpacked;
338 gsize gsm_unpacked_len;
339 gsize i;
340
341 /* unpack operation needs input length in SEPTETS */
342 gsm_unpacked = charset_gsm_unpack (gsm_packed, gsm_packed_len * 8 / 7, 0, &gsm_unpacked_len);
343
344 /* worst case initial length */
345 utf8 = g_byte_array_sized_new (gsm_unpacked_len * 2 + 1);
346
347 for (i = 0; i < gsm_unpacked_len; i++) {
348 guint8 uchars[4];
349 guint8 ulen;
350
351 /*
352 * 0x00 is NULL (when followed only by 0x00 up to the
353 * end of (fixed byte length) message, possibly also up to
354 * FORM FEED. But 0x00 is also the code for COMMERCIAL AT
355 * when some other character (CARRIAGE RETURN if nothing else)
356 * comes after the 0x00.
357 * http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
358 *
359 * So, if we find a '@' (0x00) and all the next chars after that
360 * are also 0x00, we can consider the string finished already.
361 */
362 if (gsm_unpacked[i] == 0x00) {
363 gsize j;
364
365 for (j = i + 1; j < gsm_unpacked_len; j++) {
366 if (gsm_unpacked[j] != 0x00)
367 break;
368 }
369 if (j == gsm_unpacked_len)
370 break;
371 }
372
373 if (gsm_unpacked[i] == GSM_ESCAPE_CHAR) {
374 /* Extended alphabet, decode next char */
375 ulen = gsm_ext_char_to_utf8 (gsm_unpacked[i+1], uchars);
376 if (ulen)
377 i += 1;
378 } else {
379 /* Default alphabet */
380 ulen = gsm_def_char_to_utf8 (gsm_unpacked[i], uchars);
381 }
382
383 /* Invalid GSM-7, abort */
384 if (!ulen) {
385 g_free (gsm_unpacked);
386 g_byte_array_unref (utf8);
387 return NULL;
388 }
389
390 g_byte_array_append (utf8, &uchars[0], ulen);
391 }
392
393 g_byte_array_append (utf8, (guint8 *) "\0", 1); /* NUL terminator */
394 g_free (gsm_unpacked);
395 return (gchar *) g_byte_array_free (utf8, FALSE);
396 }
397
398 /*****************************************************************************/
399
400 gchar *
401 qmi_helpers_string_utf8_from_ucs2le (const guint8 *ucs2le,
402 gsize ucs2le_len)
403 {
404 gsize ucs2he_nchars;
405 g_autofree guint16 *ucs2he = NULL;
406
407 /* UCS2 data length given in bytes must be multiple of 2 */
408 if (ucs2le_len % 2 != 0)
409 return NULL;
410
411 /* Convert length from bytes to number of ucs2 characters */
412 ucs2he_nchars = ucs2le_len / 2;
413
414 /* We'll attempt to convert UCS2 to UTF-8, using GLib's support to convert
415 * from UTF-16 to UTF-8 (given that UCS2 is a subset of UTF-16). In order
416 * to do so, we need the input string in "host endian", so if we're in a
417 * BE system (where host endian is not little endian), we do an explicit
418 * conversion.
419 *
420 * We don't want to use g_convert() because that would mean requiring
421 * full iconv() support in the system.
422 *
423 * We're using an extra allocation always because we need to increase
424 * alignment (guint8 -> (guint16)gunichar2)
425 */
426 ucs2he = g_new (guint16, ucs2he_nchars);
427 g_assert (sizeof (guint16) * ucs2he_nchars == ucs2le_len);
428 memcpy (ucs2he, ucs2le, ucs2le_len);
429 #if G_BYTE_ORDER == G_BIG_ENDIAN
430 {
431 guint i;
432
433 for (i = 0; i < ucs2he_nchars; i++)
434 ucs2he[i] = GUINT16_FROM_LE (ucs2he[i]);
435 }
436 #endif
437 return g_utf16_to_utf8 ((const gunichar2 *)ucs2he, ucs2he_nchars, NULL, NULL, NULL);
438 }
439 /*****************************************************************************/
440
441 static gchar *
442 helpers_get_usb_driver (const gchar *device_basename)
443 {
444 static const gchar *subsystems[] = { "usbmisc", "usb" };
445 guint i;
446 gchar *driver = NULL;
447
448 for (i = 0; !driver && i < G_N_ELEMENTS (subsystems); i++) {
449 gchar *tmp;
450 gchar *path;
451
452 /* driver sysfs can be built directly using subsystem and name; e.g. for subsystem
453 * usbmisc and name cdc-wdm0:
454 * $ realpath /sys/class/usbmisc/cdc-wdm0/device/driver
455 * /sys/bus/usb/drivers/qmi_wwan
456 */
457 tmp = g_strdup_printf ("/sys/class/%s/%s/device/driver", subsystems[i], device_basename);
458 path = realpath (tmp, NULL);
459 g_free (tmp);
460
461 if (!path)
462 continue;
463
464 driver = g_path_get_basename (path);
465 g_free (path);
466 }
467
468 return driver;
469 }
470
471 QmiHelpersTransportType
472 qmi_helpers_get_transport_type (const gchar *path,
473 GError **error)
474 {
475 g_autofree gchar *device_basename = NULL;
476 g_autofree gchar *usb_driver = NULL;
477 g_autofree gchar *wwan_sysfs_path = NULL;
478 g_autofree gchar *wwan_type_sysfs_path = NULL;
479 g_autofree gchar *smdpkt_sysfs_path = NULL;
480 g_autofree gchar *rpmsg_sysfs_path = NULL;
481 gchar wwan_type[16] = { 0 };
482
483 device_basename = qmi_helpers_get_devname (path, error);
484 if (!device_basename)
485 return QMI_HELPERS_TRANSPORT_TYPE_UNKNOWN;
486
487 /* Most likely case, we have a USB driver */
488 usb_driver = helpers_get_usb_driver (device_basename);
489 if (usb_driver) {
490 if (!g_strcmp0 (usb_driver, "cdc_mbim"))
491 return QMI_HELPERS_TRANSPORT_TYPE_MBIM;
492 if (!g_strcmp0 (usb_driver, "qmi_wwan"))
493 return QMI_HELPERS_TRANSPORT_TYPE_QMUX;
494 g_set_error (error, QMI_CORE_ERROR, QMI_CORE_ERROR_FAILED,
495 "unexpected usb driver detected: %s", usb_driver);
496 return QMI_HELPERS_TRANSPORT_TYPE_UNKNOWN;
497 }
498
499 /* WWAN devices have a type attribute or protocol in their name */
500 wwan_sysfs_path = g_strdup_printf ("/sys/class/wwan/%s", device_basename);
501 if (g_file_test (wwan_sysfs_path, G_FILE_TEST_EXISTS)) {
502 wwan_type_sysfs_path = g_strdup_printf ("/sys/class/wwan/%s/type", device_basename);
503 if (qmi_helpers_read_sysfs_file (wwan_type_sysfs_path, wwan_type,
504 sizeof (wwan_type) - 1, NULL)) {
505 g_strstrip (wwan_type);
506 if (!g_strcmp0 (wwan_type, "QMI"))
507 return QMI_HELPERS_TRANSPORT_TYPE_QMUX;
508 if (!g_strcmp0 (wwan_type, "MBIM"))
509 return QMI_HELPERS_TRANSPORT_TYPE_MBIM;
510 } else {
511 /* "type" attribute exists only on Linux 5.14+, fall back to device name */
512 if (g_strrstr (device_basename, "QMI"))
513 return QMI_HELPERS_TRANSPORT_TYPE_QMUX;
514 if (g_strrstr (device_basename, "MBIM"))
515 return QMI_HELPERS_TRANSPORT_TYPE_MBIM;
516 }
517 g_set_error (error, QMI_CORE_ERROR, QMI_CORE_ERROR_FAILED,
518 "unsupported wwan port");
519 return QMI_HELPERS_TRANSPORT_TYPE_UNKNOWN;
520 }
521
522 /* On Android systems we get access to the QMI control port through
523 * virtual smdcntl devices in the smdpkt subsystem. */
524 smdpkt_sysfs_path = g_strdup_printf ("/sys/class/smdpkt/%s", device_basename);
525 if (g_file_test (smdpkt_sysfs_path, G_FILE_TEST_EXISTS))
526 return QMI_HELPERS_TRANSPORT_TYPE_QMUX;
527
528 /* On mainline kernels this control port is provided by rpmsg */
529 rpmsg_sysfs_path = g_strdup_printf ("/sys/class/rpmsg/%s", device_basename);
530 if (g_file_test (rpmsg_sysfs_path, G_FILE_TEST_EXISTS))
531 return QMI_HELPERS_TRANSPORT_TYPE_QMUX;
532
533 /* Allow libqmi to connect directly to a unix domain socket with a specific file name */
534 if (g_strrstr (device_basename, QMI_QMUX_SOCKET_FILE_NAME))
535 return QMI_HELPERS_TRANSPORT_TYPE_QMUX;
536
537 g_set_error (error, QMI_CORE_ERROR, QMI_CORE_ERROR_FAILED,
538 "unexpected port subsystem");
539 return QMI_HELPERS_TRANSPORT_TYPE_UNKNOWN;
540 }
541
542 gchar *
543 qmi_helpers_get_devpath (const gchar *cdc_wdm_path,
544 GError **error)
545 {
546 gchar *aux;
547
548 if (!g_file_test (cdc_wdm_path, G_FILE_TEST_IS_SYMLINK))
549 return g_strdup (cdc_wdm_path);
550
551 aux = realpath (cdc_wdm_path, NULL);
552 if (!aux) {
553 int saved_errno = errno;
554
555 g_set_error (error, QMI_CORE_ERROR, QMI_CORE_ERROR_FAILED,
556 "Couldn't get realpath: %s", g_strerror (saved_errno));
557 return NULL;
558 }
559
560 return aux;
561 }
562
563 gchar *
564 qmi_helpers_get_devname (const gchar *cdc_wdm_path,
565 GError **error)
566 {
567 gchar *aux;
568 gchar *devname = NULL;
569
570 aux = qmi_helpers_get_devpath (cdc_wdm_path, error);
571 if (aux) {
572 devname = g_path_get_basename (aux);
573 g_free (aux);
574 }
575
576 return devname;
577 }
578
579 gboolean
580 qmi_helpers_read_sysfs_file (const gchar *sysfs_path,
581 gchar *out_value,
582 guint max_read_size,
583 GError **error)
584 {
585 FILE *f;
586 gboolean status = FALSE;
587
588 if (!(f = fopen (sysfs_path, "r"))) {
589 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
590 "Failed to open sysfs file '%s': %s",
591 sysfs_path, g_strerror (errno));
592 goto out;
593 }
594
595 if (fread (out_value, 1, max_read_size, f) == 0) {
596 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
597 "Failed to read from sysfs file '%s': %s",
598 sysfs_path, g_strerror (errno));
599 goto out;
600 }
601
602 status = TRUE;
603
604 out:
605 if (f)
606 fclose (f);
607 return status;
608 }
609
610 gboolean
611 qmi_helpers_write_sysfs_file (const gchar *sysfs_path,
612 const gchar *value,
613 GError **error)
614 {
615 gboolean status = FALSE;
616 FILE *f;
617 guint value_len;
618
619 if (!(f = fopen (sysfs_path, "w"))) {
620 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
621 "Failed to open sysfs file '%s' for R/W: %s",
622 sysfs_path, g_strerror (errno));
623 goto out;
624 }
625
626 /* we require unbuffered so that we get errors on the fwrite() */
627 setvbuf (f, NULL, _IONBF, 0);
628
629 value_len = strlen (value);
630 if ((fwrite (value, 1, value_len, f) != value_len) || ferror (f)) {
631 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
632 "Failed to write to sysfs file '%s': %s",
633 sysfs_path, g_strerror (errno));
634 goto out;
635 }
636
637 status = TRUE;
638
639 out:
640 if (f)
641 fclose (f);
642 return status;
643 }
644
645 /******************************************************************************/
646
647 gboolean
648 qmi_helpers_list_links (GFile *sysfs_file,
649 GCancellable *cancellable,
650 GPtrArray *previous_links,
651 GPtrArray **out_links,
652 GError **error)
653 {
654 g_autofree gchar *sysfs_path = NULL;
655 g_autoptr(GFileEnumerator) direnum = NULL;
656 g_autoptr(GPtrArray) links = NULL;
657
658 direnum = g_file_enumerate_children (sysfs_file,
659 G_FILE_ATTRIBUTE_STANDARD_NAME,
660 G_FILE_QUERY_INFO_NONE,
661 cancellable,
662 error);
663 if (!direnum)
664 return FALSE;
665
666 sysfs_path = g_file_get_path (sysfs_file);
667 links = g_ptr_array_new_with_free_func (g_free);
668
669 while (TRUE) {
670 GFileInfo *info;
671 g_autofree gchar *filename = NULL;
672 g_autofree gchar *link_path = NULL;
673 g_autofree gchar *real_path = NULL;
674 g_autofree gchar *basename = NULL;
675
676 if (!g_file_enumerator_iterate (direnum, &info, NULL, cancellable, error))
677 return FALSE;
678 if (!info)
679 break;
680
681 filename = g_file_info_get_attribute_as_string (info, G_FILE_ATTRIBUTE_STANDARD_NAME);
682 if (!filename || !g_str_has_prefix (filename, "upper_"))
683 continue;
684
685 link_path = g_strdup_printf ("%s/%s", sysfs_path, filename);
686 real_path = realpath (link_path, NULL);
687 if (!real_path)
688 continue;
689
690 basename = g_path_get_basename (real_path);
691
692 /* skip interface if it was already known */
693 if (previous_links && g_ptr_array_find_with_equal_func (previous_links, basename, g_str_equal, NULL))
694 continue;
695
696 g_ptr_array_add (links, g_steal_pointer (&basename));
697 }
698
699 if (!links || !links->len) {
700 *out_links = NULL;
701 return TRUE;
702 }
703
704 g_ptr_array_sort (links, (GCompareFunc) g_ascii_strcasecmp);
705 *out_links = g_steal_pointer (&links);
706 return TRUE;
707 }
708
709 /******************************************************************************/
710
711 void
712 qmi_helpers_clear_string (gchar **value)
713 {
714 if (value && *value)
715 g_free (*value);
716 }
717
718 /******************************************************************************/
719
720 #if !GLIB_CHECK_VERSION(2,54,0)
721
722 gboolean
723 qmi_ptr_array_find_with_equal_func (GPtrArray *haystack,
724 gconstpointer needle,
725 GEqualFunc equal_func,
726 guint *index_)
727 {
728 guint i;
729
730 g_return_val_if_fail (haystack != NULL, FALSE);
731
732 if (equal_func == NULL)
733 equal_func = g_direct_equal;
734
735 for (i = 0; i < haystack->len; i++) {
736 if (equal_func (g_ptr_array_index (haystack, i), needle)) {
737 if (index_ != NULL)
738 *index_ = i;
739 return TRUE;
740 }
741 }
742
743 return FALSE;
744 }
745
746 #endif