Debian Codegraph @

src/registry.c

raw
1 /*
2 * Copyright © 2020 Red Hat, Inc.
3 * SPDX-License-Identifier: MIT
4 */
5
6 #include "config.h"
7
8 #include <assert.h>
9 #include <sys/stat.h>
10 #include <fcntl.h>
11 #include <stdbool.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <stdint.h>
15 #include <libxml/parser.h>
16
17 #if HAVE_XKB_EXTENSIONS_DIRECTORIES
18 #include <limits.h>
19 #if HAVE_UNISTD_H && HAVE_DIRENT_H
20 #include <dirent.h>
21 #include <unistd.h>
22 #endif
23 #endif
24
25 #include "xkbcommon/xkbregistry.h"
26 #include "messages-codes.h"
27 #include "utils.h"
28 #include "util-list.h"
29 #include "util-mem.h"
30
31 struct rxkb_object;
32
33 /**
34 * All our objects are refcounted and are linked to iterate through them.
35 * Abstract those bits away into a shared parent class so we can generate
36 * most of the functions through macros.
37 */
38 struct rxkb_object {
39 struct rxkb_object *parent;
40 uint32_t refcount;
41 struct list link;
42 };
43
44 struct rxkb_iso639_code {
45 struct rxkb_object base;
46 char *code;
47 };
48
49 struct rxkb_iso3166_code {
50 struct rxkb_object base;
51 char *code;
52 };
53
54 enum context_state {
55 CONTEXT_NEW,
56 CONTEXT_PARSED,
57 CONTEXT_FAILED,
58 };
59
60 struct rxkb_context {
61 struct rxkb_object base;
62 enum context_state context_state;
63
64 bool load_extra_rules_files;
65 bool use_secure_getenv;
66
67 struct list models; /* list of struct rxkb_models */
68 struct list layouts; /* list of struct rxkb_layouts */
69 struct list option_groups; /* list of struct rxkb_option_group */
70
71 darray(char *) includes;
72
73
74 ATTR_PRINTF(3, 0) void (*log_fn)(struct rxkb_context *ctx,
75 enum rxkb_log_level level,
76 const char *fmt, va_list args);
77 enum rxkb_log_level log_level;
78
79 void *userdata;
80 };
81
82 struct rxkb_model {
83 struct rxkb_object base;
84
85 char *name;
86 char *vendor;
87 char *description;
88 enum rxkb_popularity popularity;
89 };
90
91 struct rxkb_layout {
92 struct rxkb_object base;
93
94 char *name;
95 char *brief;
96 char *description;
97 char *variant;
98 enum rxkb_popularity popularity;
99
100 struct list iso639s; /* list of struct rxkb_iso639_code */
101 struct list iso3166s; /* list of struct rxkb_iso3166_code */
102 };
103
104 struct rxkb_option_group {
105 struct rxkb_object base;
106
107 bool allow_multiple;
108 struct list options; /* list of struct rxkb_options */
109 char *name;
110 char *description;
111 enum rxkb_popularity popularity;
112 };
113
114 struct rxkb_option {
115 struct rxkb_object base;
116
117 char *name;
118 char *brief;
119 char *description;
120 enum rxkb_popularity popularity;
121 bool layout_specific;
122 };
123
124 static bool
125 parse(struct rxkb_context *ctx, const char *path,
126 enum rxkb_popularity popularity);
127
128 ATTR_PRINTF(3, 4)
129 static void
130 rxkb_log(struct rxkb_context *ctx, enum rxkb_log_level level,
131 const char *fmt, ...)
132 {
133 va_list args;
134
135 if (ctx->log_level < level)
136 return;
137
138 va_start(args, fmt);
139 ctx->log_fn(ctx, level, fmt, args);
140 va_end(args);
141 }
142
143 /*
144 * The format is not part of the argument list in order to avoid the
145 * "ISO C99 requires rest arguments to be used" warning when only the
146 * format is supplied without arguments. Not supplying it would still
147 * result in an error, though.
148 */
149 #define rxkb_log_with_code(ctx, level, msg_id, fmt, ...) \
150 rxkb_log(ctx, level, PREPEND_MESSAGE_ID(msg_id, fmt), ##__VA_ARGS__)
151 #define log_dbg(ctx, ...) \
152 rxkb_log((ctx), RXKB_LOG_LEVEL_DEBUG, __VA_ARGS__)
153 #define log_info(ctx, id, ...) \
154 rxkb_log_with_code((ctx), RXKB_LOG_LEVEL_INFO, id, __VA_ARGS__)
155 #define log_warn(ctx, id, ...) \
156 rxkb_log_with_code((ctx), RXKB_LOG_LEVEL_WARNING, id, __VA_ARGS__)
157 #define log_err(ctx, id, ...) \
158 rxkb_log_with_code((ctx), RXKB_LOG_LEVEL_ERROR, id, __VA_ARGS__)
159 #define log_wsgo(ctx, id, ...) \
160 rxkb_log_with_code((ctx), RXKB_LOG_LEVEL_CRITICAL, id, __VA_ARGS__)
161
162
163 #define DECLARE_REF_UNREF_FOR_TYPE(type_) \
164 struct type_ * type_##_ref(struct type_ *object) { \
165 rxkb_object_ref(&object->base); \
166 return object; \
167 } \
168 struct type_ * type_##_unref(struct type_ *object) { \
169 if (!object) return NULL; \
170 assert(object->base.refcount >= 1); \
171 if (--object->base.refcount == 0) {\
172 type_##_destroy(object); \
173 list_remove(&object->base.link);\
174 free(object); \
175 } \
176 return NULL;\
177 }
178
179 #define DECLARE_CREATE_FOR_TYPE(type_) \
180 static inline struct type_ * type_##_create(struct rxkb_object *parent) { \
181 struct type_ *t = calloc(1, sizeof *t); \
182 if (t) \
183 rxkb_object_init(&t->base, parent); \
184 return t; \
185 }
186
187 #define DECLARE_TYPED_GETTER_FOR_TYPE(type_, field_, rtype_) \
188 rtype_ type_##_get_##field_(struct type_ *object) { \
189 return object->field_; \
190 }
191
192 #define DECLARE_GETTER_FOR_TYPE(type_, field_) \
193 DECLARE_TYPED_GETTER_FOR_TYPE(type_, field_, const char*)
194
195 #define DECLARE_FIRST_NEXT_FOR_TYPE(type_, parent_type_, parent_field_) \
196 struct type_ * type_##_first(struct parent_type_ *parent) { \
197 struct type_ *o = NULL; \
198 if (!list_empty(&parent->parent_field_)) \
199 o = list_first_entry(&parent->parent_field_, o, base.link); \
200 return o; \
201 } \
202 struct type_ * \
203 type_##_next(struct type_ *o) \
204 { \
205 struct parent_type_ *parent; \
206 struct type_ *next; \
207 parent = container_of(o->base.parent, struct parent_type_, base); \
208 next = list_first_entry(&o->base.link, o, base.link); \
209 if (list_is_last(&parent->parent_field_, &o->base.link)) \
210 return NULL; \
211 return next; \
212 }
213
214 static void
215 rxkb_object_init(struct rxkb_object *object, struct rxkb_object *parent)
216 {
217 object->refcount = 1;
218 object->parent = parent;
219 list_init(&object->link);
220 }
221
222 static void *
223 rxkb_object_ref(struct rxkb_object *object)
224 {
225 assert(object->refcount >= 1);
226 ++object->refcount;
227 return object;
228 }
229
230 static void
231 rxkb_iso639_code_destroy(struct rxkb_iso639_code *code)
232 {
233 free(code->code);
234 }
235
236 struct rxkb_iso639_code *
237 rxkb_layout_get_iso639_first(struct rxkb_layout *layout)
238 {
239 struct rxkb_iso639_code *code = NULL;
240
241 if (!list_empty(&layout->iso639s))
242 code = list_first_entry(&layout->iso639s, code, base.link);
243
244 return code;
245 }
246
247 struct rxkb_iso639_code *
248 rxkb_iso639_code_next(struct rxkb_iso639_code *code)
249 {
250 struct rxkb_iso639_code *next = NULL;
251 struct rxkb_layout *layout;
252
253 layout = container_of(code->base.parent, struct rxkb_layout, base);
254
255 if (list_is_last(&layout->iso639s, &code->base.link))
256 return NULL;
257
258 next = list_first_entry(&code->base.link, code, base.link);
259
260 return next;
261 }
262
263 DECLARE_REF_UNREF_FOR_TYPE(rxkb_iso639_code);
264 DECLARE_CREATE_FOR_TYPE(rxkb_iso639_code);
265 DECLARE_GETTER_FOR_TYPE(rxkb_iso639_code, code);
266
267 static void
268 rxkb_iso3166_code_destroy(struct rxkb_iso3166_code *code)
269 {
270 free(code->code);
271 }
272
273 struct rxkb_iso3166_code *
274 rxkb_layout_get_iso3166_first(struct rxkb_layout *layout)
275 {
276 struct rxkb_iso3166_code *code = NULL;
277
278 if (!list_empty(&layout->iso3166s))
279 code = list_first_entry(&layout->iso3166s, code, base.link);
280
281 return code;
282 }
283
284 struct rxkb_iso3166_code *
285 rxkb_iso3166_code_next(struct rxkb_iso3166_code *code)
286 {
287 struct rxkb_iso3166_code *next = NULL;
288 struct rxkb_layout *layout;
289
290 layout = container_of(code->base.parent, struct rxkb_layout, base);
291
292 if (list_is_last(&layout->iso3166s, &code->base.link))
293 return NULL;
294
295 next = list_first_entry(&code->base.link, code, base.link);
296
297 return next;
298 }
299
300 DECLARE_REF_UNREF_FOR_TYPE(rxkb_iso3166_code);
301 DECLARE_CREATE_FOR_TYPE(rxkb_iso3166_code);
302 DECLARE_GETTER_FOR_TYPE(rxkb_iso3166_code, code);
303
304 static void
305 rxkb_option_destroy(struct rxkb_option *o)
306 {
307 free(o->name);
308 free(o->brief);
309 free(o->description);
310 }
311
312 DECLARE_REF_UNREF_FOR_TYPE(rxkb_option);
313 DECLARE_CREATE_FOR_TYPE(rxkb_option);
314 DECLARE_GETTER_FOR_TYPE(rxkb_option, name);
315 DECLARE_GETTER_FOR_TYPE(rxkb_option, brief);
316 DECLARE_GETTER_FOR_TYPE(rxkb_option, description);
317 DECLARE_TYPED_GETTER_FOR_TYPE(rxkb_option, popularity, enum rxkb_popularity);
318 bool rxkb_option_is_layout_specific(struct rxkb_option *object) {
319 return object->layout_specific;
320 }
321 DECLARE_FIRST_NEXT_FOR_TYPE(rxkb_option, rxkb_option_group, options);
322
323 static void
324 rxkb_layout_destroy(struct rxkb_layout *l)
325 {
326 struct rxkb_iso639_code *iso639, *tmp_639;
327 struct rxkb_iso3166_code *iso3166, *tmp_3166;
328
329 free(l->name);
330 free(l->brief);
331 free(l->description);
332 free(l->variant);
333
334 list_for_each_safe(iso639, tmp_639, &l->iso639s, base.link) {
335 rxkb_iso639_code_unref(iso639);
336 }
337 list_for_each_safe(iso3166, tmp_3166, &l->iso3166s, base.link) {
338 rxkb_iso3166_code_unref(iso3166);
339 }
340 }
341
342 DECLARE_REF_UNREF_FOR_TYPE(rxkb_layout);
343 DECLARE_CREATE_FOR_TYPE(rxkb_layout);
344 DECLARE_GETTER_FOR_TYPE(rxkb_layout, name);
345 DECLARE_GETTER_FOR_TYPE(rxkb_layout, brief);
346 DECLARE_GETTER_FOR_TYPE(rxkb_layout, description);
347 DECLARE_GETTER_FOR_TYPE(rxkb_layout, variant);
348 DECLARE_TYPED_GETTER_FOR_TYPE(rxkb_layout, popularity, enum rxkb_popularity);
349 DECLARE_FIRST_NEXT_FOR_TYPE(rxkb_layout, rxkb_context, layouts);
350
351 static void
352 rxkb_model_destroy(struct rxkb_model *m)
353 {
354 free(m->name);
355 free(m->vendor);
356 free(m->description);
357 }
358
359 DECLARE_REF_UNREF_FOR_TYPE(rxkb_model);
360 DECLARE_CREATE_FOR_TYPE(rxkb_model);
361 DECLARE_GETTER_FOR_TYPE(rxkb_model, name);
362 DECLARE_GETTER_FOR_TYPE(rxkb_model, vendor);
363 DECLARE_GETTER_FOR_TYPE(rxkb_model, description);
364 DECLARE_TYPED_GETTER_FOR_TYPE(rxkb_model, popularity, enum rxkb_popularity);
365 DECLARE_FIRST_NEXT_FOR_TYPE(rxkb_model, rxkb_context, models);
366
367 static void
368 rxkb_option_group_destroy(struct rxkb_option_group *og)
369 {
370 struct rxkb_option *o, *otmp;
371
372 free(og->name);
373 free(og->description);
374
375 list_for_each_safe(o, otmp, &og->options, base.link) {
376 rxkb_option_unref(o);
377 }
378 }
379
380 bool
381 rxkb_option_group_allows_multiple(struct rxkb_option_group *g)
382 {
383 return g->allow_multiple;
384 }
385
386 DECLARE_REF_UNREF_FOR_TYPE(rxkb_option_group);
387 DECLARE_CREATE_FOR_TYPE(rxkb_option_group);
388 DECLARE_GETTER_FOR_TYPE(rxkb_option_group, name);
389 DECLARE_GETTER_FOR_TYPE(rxkb_option_group, description);
390 DECLARE_TYPED_GETTER_FOR_TYPE(rxkb_option_group, popularity, enum rxkb_popularity);
391 DECLARE_FIRST_NEXT_FOR_TYPE(rxkb_option_group, rxkb_context, option_groups);
392
393 static void
394 rxkb_context_destroy(struct rxkb_context *ctx)
395 {
396 struct rxkb_model *m, *mtmp;
397 struct rxkb_layout *l, *ltmp;
398 struct rxkb_option_group *og, *ogtmp;
399 char **path;
400
401 list_for_each_safe(m, mtmp, &ctx->models, base.link)
402 rxkb_model_unref(m);
403 assert(list_empty(&ctx->models));
404
405 list_for_each_safe(l, ltmp, &ctx->layouts, base.link)
406 rxkb_layout_unref(l);
407 assert(list_empty(&ctx->layouts));
408
409 list_for_each_safe(og, ogtmp, &ctx->option_groups, base.link)
410 rxkb_option_group_unref(og);
411 assert(list_empty(&ctx->option_groups));
412
413 darray_foreach(path, ctx->includes)
414 free(*path);
415 darray_free(ctx->includes);
416
417 assert(darray_empty(ctx->includes));
418 }
419
420 DECLARE_REF_UNREF_FOR_TYPE(rxkb_context);
421 DECLARE_CREATE_FOR_TYPE(rxkb_context);
422 DECLARE_TYPED_GETTER_FOR_TYPE(rxkb_context, log_level, enum rxkb_log_level);
423
424 static char *
425 rxkb_context_getenv(struct rxkb_context *ctx, const char *name)
426 {
427 if (ctx->use_secure_getenv) {
428 return secure_getenv(name);
429 } else {
430 return getenv(name);
431 }
432 }
433
434
435 void
436 rxkb_context_set_log_level(struct rxkb_context *ctx,
437 enum rxkb_log_level level)
438 {
439 ctx->log_level = level;
440 }
441
442 static const char *
443 log_level_to_prefix(enum rxkb_log_level level)
444 {
445 switch (level) {
446 case RXKB_LOG_LEVEL_DEBUG:
447 return "xkbregistry: DEBUG: ";
448 case RXKB_LOG_LEVEL_INFO:
449 return "xkbregistry: INFO: ";
450 case RXKB_LOG_LEVEL_WARNING:
451 return "xkbregistry: WARNING: ";
452 case RXKB_LOG_LEVEL_ERROR:
453 return "xkbregistry: ERROR: ";
454 case RXKB_LOG_LEVEL_CRITICAL:
455 return "xkbregistry: CRITICAL: ";
456 default:
457 return NULL;
458 }
459 }
460
461 ATTR_PRINTF(3, 0) static void
462 default_log_fn(struct rxkb_context *ctx, enum rxkb_log_level level,
463 const char *fmt, va_list args)
464 {
465 const char *prefix = log_level_to_prefix(level);
466
467 if (prefix)
468 fprintf(stderr, "%s", prefix);
469 vfprintf(stderr, fmt, args);
470 }
471
472 static enum rxkb_log_level
473 log_level(const char *level) {
474 char *endptr;
475 enum rxkb_log_level lvl;
476
477 errno = 0;
478 lvl = strtol(level, &endptr, 10);
479 if (errno == 0 && (endptr[0] == '\0' || is_space(endptr[0])))
480 return lvl;
481 if (istreq_prefix("crit", level))
482 return RXKB_LOG_LEVEL_CRITICAL;
483 if (istreq_prefix("err", level))
484 return RXKB_LOG_LEVEL_ERROR;
485 if (istreq_prefix("warn", level))
486 return RXKB_LOG_LEVEL_WARNING;
487 if (istreq_prefix("info", level))
488 return RXKB_LOG_LEVEL_INFO;
489 if (istreq_prefix("debug", level) || istreq_prefix("dbg", level))
490 return RXKB_LOG_LEVEL_DEBUG;
491
492 return RXKB_LOG_LEVEL_ERROR;
493 }
494
495 struct rxkb_context *
496 rxkb_context_new(enum rxkb_context_flags flags)
497 {
498 struct rxkb_context *ctx = rxkb_context_create(NULL);
499 const char *env;
500
501 if (!ctx)
502 return NULL;
503
504 ctx->context_state = CONTEXT_NEW;
505 ctx->load_extra_rules_files = flags & RXKB_CONTEXT_LOAD_EXOTIC_RULES;
506 ctx->use_secure_getenv = !(flags & RXKB_CONTEXT_NO_SECURE_GETENV);
507 ctx->log_fn = default_log_fn;
508 ctx->log_level = RXKB_LOG_LEVEL_ERROR;
509
510 /* Environment overwrites defaults. */
511 env = rxkb_context_getenv(ctx, "RXKB_LOG_LEVEL");
512 if (env)
513 rxkb_context_set_log_level(ctx, log_level(env));
514
515 list_init(&ctx->models);
516 list_init(&ctx->layouts);
517 list_init(&ctx->option_groups);
518
519 if (!(flags & RXKB_CONTEXT_NO_DEFAULT_INCLUDES) &&
520 !rxkb_context_include_path_append_default(ctx)) {
521 log_err(ctx, XKB_ERROR_NO_VALID_DEFAULT_INCLUDE_PATH,
522 "Failed to add any default include path "
523 "(default system path: %s)\n",
524 DFLT_XKB_CONFIG_ROOT);
525 rxkb_context_unref(ctx);
526 return NULL;
527 }
528
529 return ctx;
530 }
531
532 void
533 rxkb_context_set_log_fn(struct rxkb_context *ctx,
534 void (*log_fn)(struct rxkb_context *ctx,
535 enum rxkb_log_level level,
536 const char *fmt, va_list args))
537 {
538 ctx->log_fn = (log_fn ? log_fn : default_log_fn);
539 }
540
541 bool
542 rxkb_context_include_path_append(struct rxkb_context *ctx, const char *path)
543 {
544 int err = 0;
545
546 if (ctx->context_state != CONTEXT_NEW) {
547 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
548 "include paths can only be appended to a new context\n");
549 goto error;
550 }
551
552 struct stat stat_buf;
553 err = stat(path, &stat_buf);
554 if (err != 0) {
555 err = errno;
556 goto error;
557 }
558 if (!S_ISDIR(stat_buf.st_mode)) {
559 err = ENOTDIR;
560 goto error;
561 }
562
563 if (!check_eaccess(path, R_OK | X_OK)) {
564 err = EACCES;
565 goto error;
566 }
567
568 /*
569 * Pre-filter for the 99.9% case - if we can’t assemble the default ruleset
570 * path, complain here instead of during parsing later. The niche cases
571 * where this is the wrong behaviour aren’t worth worrying about.
572 */
573 char rules[PATH_MAX];
574 if (!snprintf_safe(rules, sizeof(rules), "%s/rules/%s.xml",
575 path, DEFAULT_XKB_RULES)) {
576 log_err(ctx, XKB_ERROR_INVALID_PATH,
577 "Path is too long: expected max length of %zu, "
578 "got: %s/rules/%s.xml\n",
579 sizeof(rules), path, DEFAULT_XKB_RULES);
580 goto error;
581 }
582
583 char * const tmp = strdup(path);
584 if (!tmp) {
585 err = ENOMEM;
586 goto error;
587 }
588
589 darray_append(ctx->includes, tmp);
590 /* Use “info” log level to facilitate bug reporting. */
591 log_info(ctx, XKB_LOG_MESSAGE_NO_ID, "Include path added: %s\n", tmp);
592
593 return true;
594
595 error:
596 /*
597 * This error is not fatal because some valid paths may still be defined.
598 * Use “info” log level to facilitate bug reporting.
599 */
600 log_info(ctx, XKB_LOG_MESSAGE_NO_ID,
601 "Include path failed: \"%s\" (%s)\n", path, strerror(err));
602 return false;
603 }
604
605 #ifdef HAVE_XKB_EXTENSIONS_DIRECTORIES
606
607 static int
608 compare_str(const void *a, const void *b)
609 {
610 return strcmp(*(char **)a, *(char **) b);
611 }
612
613 static int
614 add_direct_subdirectories(struct rxkb_context *ctx, const char *path,
615 darray_string *extensions,
616 darray_size_t versioned_count,
617 size_t versioned_path_length)
618 {
619 int ret = 0;
620 int err = ENOMEM;
621 DIR *dir = NULL;
622
623 /* Check extensions parent directory */
624 struct stat stat_buf;
625 err = stat(path, &stat_buf);
626 if (err != 0) {
627 err = errno;
628 goto err;
629 }
630 if (!S_ISDIR(stat_buf.st_mode)) {
631 err = ENOTDIR;
632 goto err;
633 }
634 if (!check_eaccess(path, R_OK | X_OK)) {
635 err = EACCES;
636 goto err;
637 }
638
639 dir = opendir(path);
640 if (dir == NULL) {
641 err = EACCES;
642 goto err;
643 }
644
645 struct dirent *entry;
646 char path_buf[PATH_MAX] = "";
647 versioned_path_length++; /* Additional final ‘/’ */
648 while ((entry = readdir(dir)) != NULL) {
649 const char *name = entry->d_name;
650
651 /* Skip special entries */
652 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0)
653 continue;
654
655 if (!snprintf_safe(path_buf, sizeof(path_buf), "%s/%s", path, name)) {
656 err = ENOMEM;
657 goto err;
658 }
659 if (stat(path_buf, &stat_buf) != 0 || !S_ISDIR(stat_buf.st_mode))
660 continue;
661
662 /* Skip if the corresponding versioned directory is already included */
663 for (darray_size_t i = 0; i < versioned_count; i++) {
664 const char * const prev_name = darray_item(*extensions, i)
665 + versioned_path_length;
666 if (strcmp(name, prev_name) == 0)
667 goto next;
668 }
669
670 char *ext_path = strdup_safe(path_buf);
671 if (!ext_path) {
672 err = ENOMEM;
673 goto err;
674 }
675
676 darray_append(*extensions, ext_path);
677 next:
678 {} /* Label at end of compound statement is a C23 extension */
679 }
680
681 closedir(dir);
682
683 if (darray_size(*extensions) > versioned_count) {
684 /* Sort the entries, so that they are appended in lexicographic order */
685 qsort(darray_items(*extensions) + versioned_count,
686 darray_size(*extensions) - versioned_count,
687 sizeof(*darray_items(*extensions)), &compare_str);
688 char **ext_path;
689 darray_foreach_from(ext_path, *extensions, versioned_count) {
690 ret |= rxkb_context_include_path_append(ctx, *ext_path);
691 }
692 }
693
694 return ret;
695
696 err:
697 log_dbg(ctx,
698 "Include extensions path failed: %s (%s)\n", path, strerror(err));
699 if (dir)
700 closedir(dir);
701
702 return ret;
703 }
704 #endif
705
706 bool
707 rxkb_context_include_path_append_default(struct rxkb_context *ctx)
708 {
709 char user_path[PATH_MAX];
710 bool ret = false;
711
712 if (ctx->context_state != CONTEXT_NEW) {
713 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
714 "include paths can only be appended to a new context\n");
715 return false;
716 }
717
718 const char * const home = rxkb_context_getenv(ctx, "HOME");
719 const char * const xdg = rxkb_context_getenv(ctx, "XDG_CONFIG_HOME");
720 /* Accept empty string, which may be unintentional and should be reported */
721 if (xdg != NULL) {
722 if (snprintf_safe(user_path, sizeof(user_path), "%s/xkb", xdg))
723 ret |= rxkb_context_include_path_append(ctx, user_path);
724 } else if (home != NULL) {
725 /* XDG_CONFIG_HOME fallback is $HOME/.config/ */
726 if (snprintf_safe(user_path, sizeof(user_path), "%s/.config/xkb", home))
727 ret |= rxkb_context_include_path_append(ctx, user_path);
728 }
729
730 if (home != NULL) {
731 if (snprintf_safe(user_path, sizeof(user_path), "%s/.xkb", home))
732 ret |= rxkb_context_include_path_append(ctx, user_path);
733 }
734
735 const char * const extra = rxkb_context_getenv(ctx, "XKB_CONFIG_EXTRA_PATH");
736 /*
737 * Only use default if path is undefined, but accept empty string, which may
738 * be unintentional and should be reported.
739 */
740 ret |= rxkb_context_include_path_append(
741 ctx, ((extra != NULL) ? extra : DFLT_XKB_CONFIG_EXTRA_PATH)
742 );
743
744 #ifdef HAVE_XKB_EXTENSIONS_DIRECTORIES
745 darray_string extensions = darray_new();
746
747 /* Versioned extensions directory */
748 const char *extensions_path =
749 rxkb_context_getenv(ctx, "XKB_CONFIG_VERSIONED_EXTENSIONS_PATH");
750 #ifdef DFLT_XKB_CONFIG_VERSIONED_EXTENSIONS_PATH
751 if (extensions_path == NULL)
752 extensions_path = DFLT_XKB_CONFIG_VERSIONED_EXTENSIONS_PATH;
753 #endif
754 size_t versioned_path_length = 0;
755 if (extensions_path != NULL) {
756 /* Add direct subdirectories */
757 ret |= add_direct_subdirectories(ctx, extensions_path,
758 &extensions, 0, 0);
759 versioned_path_length = strlen(extensions_path);
760 }
761
762 /* Unversioned extensions directory */
763 extensions_path =
764 rxkb_context_getenv(ctx, "XKB_CONFIG_UNVERSIONED_EXTENSIONS_PATH");
765 #ifdef DFLT_XKB_CONFIG_UNVERSIONED_EXTENSIONS_PATH
766 if (extensions_path == NULL)
767 extensions_path = DFLT_XKB_CONFIG_UNVERSIONED_EXTENSIONS_PATH;
768 #endif
769 if (extensions_path != NULL) {
770 /*
771 * Add direct subdirectories, except those already added from the
772 * *versioned* extensions path hereinabove.
773 */
774 ret |= add_direct_subdirectories(ctx, extensions_path, &extensions,
775 darray_size(extensions),
776 versioned_path_length);
777 }
778
779 char **ext_path;
780 darray_foreach(ext_path, extensions) {
781 free(*ext_path);
782 }
783 darray_free(extensions);
784 #endif
785
786 /* Canonical XKB root */
787 const char * const root = rxkb_context_getenv(ctx, "XKB_CONFIG_ROOT");
788 /*
789 * Only use default if path is undefined, but accept empty string, which may
790 * be unintentional and should be reported.
791 */
792 const bool has_root = rxkb_context_include_path_append(
793 ctx, ((root != NULL) ? root: DFLT_XKB_CONFIG_ROOT)
794 );
795 ret |= has_root;
796
797 /*
798 * Fallback for misconfigured setups.
799 * Some setups use the assumption that the canonical XKB root is always the
800 * legacy X11 one, but this is no longer true since xkeyboard-config 2.45,
801 * where the X11 path is now a mere symlink to a dedicated xkeyboard-config
802 * data directory.
803 * This fallback can still be skipped if deliberately using an empty string
804 * for the canonical XKB root hereinabove.
805 */
806 if (!has_root && (root == NULL || root[0] != '\0')) {
807 log_warn(ctx, XKB_LOG_MESSAGE_NO_ID,
808 "Root include path failed; fallback to \"%s\". "
809 "The setup is probably misconfigured. "
810 "Please ensure that \"%s\" is available in the environment.\n",
811 DFLT_XKB_LEGACY_ROOT,
812 ((root == NULL) ? DFLT_XKB_CONFIG_ROOT : root));
813 ret |= rxkb_context_include_path_append(ctx, DFLT_XKB_LEGACY_ROOT);
814 }
815
816 return ret;
817 }
818
819 bool
820 rxkb_context_parse_default_ruleset(struct rxkb_context *ctx)
821 {
822 return rxkb_context_parse(ctx, DEFAULT_XKB_RULES);
823 }
824
825 bool
826 rxkb_context_parse(struct rxkb_context *ctx, const char *ruleset)
827 {
828 char **path;
829 bool success = false;
830
831 if (ctx->context_state != CONTEXT_NEW) {
832 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
833 "parse must only be called on a new context\n");
834 return false;
835 }
836
837 darray_foreach_reverse(path, ctx->includes) {
838 char rules[PATH_MAX];
839
840 if (snprintf_safe(rules, sizeof(rules), "%s/rules/%s.xml",
841 *path, ruleset)) {
842 log_dbg(ctx, "Parsing %s\n", rules);
843 if (parse(ctx, rules, RXKB_POPULARITY_STANDARD))
844 success = true;
845 }
846
847 if (ctx->load_extra_rules_files &&
848 snprintf_safe(rules, sizeof(rules), "%s/rules/%s.extras.xml",
849 *path, ruleset)) {
850 log_dbg(ctx, "Parsing %s\n", rules);
851 if (parse(ctx, rules, RXKB_POPULARITY_EXOTIC))
852 success = true;
853 }
854 }
855
856 ctx->context_state = success ? CONTEXT_PARSED : CONTEXT_FAILED;
857
858 return success;
859 }
860
861
862 void
863 rxkb_context_set_user_data(struct rxkb_context *ctx, void *userdata)
864 {
865 ctx->userdata = userdata;
866 }
867
868 void *
869 rxkb_context_get_user_data(struct rxkb_context *ctx)
870 {
871 return ctx->userdata;
872 }
873
874 static inline bool
875 is_node(xmlNode *node, const char *name)
876 {
877 return node->type == XML_ELEMENT_NODE &&
878 xmlStrEqual(node->name, (const xmlChar*)name);
879 }
880
881 /* return a copy of the text content from the first text node of this node */
882 static char *
883 extract_text(xmlNode *node)
884 {
885 xmlNode *n;
886
887 for (n = node->children; n; n = n->next) {
888 if (n->type == XML_TEXT_NODE)
889 return (char *)xmlStrdup(n->content);
890 }
891 return NULL;
892 }
893
894 /* Data from “configItem” node */
895 struct config_item {
896 char *name;
897 char *description;
898 char *brief;
899 char *vendor;
900 enum rxkb_popularity popularity;
901 bool layout_specific;
902 };
903
904 #define config_item_new(popularity_) { \
905 .name = NULL, \
906 .description = NULL, \
907 .brief = NULL, \
908 .vendor = NULL, \
909 .popularity = (popularity_), \
910 .layout_specific = false \
911 }
912
913 static void
914 config_item_free(struct config_item *config) {
915 free(config->name);
916 free(config->description);
917 free(config->brief);
918 free(config->vendor);
919 }
920
921 static bool
922 parse_config_item(struct rxkb_context *ctx, xmlNode *parent,
923 struct config_item *config)
924 {
925 xmlNode *node = NULL;
926 xmlNode *ci = NULL;
927
928 for (ci = parent->children; ci; ci = ci->next) {
929 if (is_node(ci, "configItem")) {
930 /* Process attributes */
931 xmlChar *raw_popularity = xmlGetProp(ci, (const xmlChar*)"popularity");
932 if (raw_popularity) {
933 if (xmlStrEqual(raw_popularity, (const xmlChar*)"standard"))
934 config->popularity = RXKB_POPULARITY_STANDARD;
935 else if (xmlStrEqual(raw_popularity, (const xmlChar*)"exotic"))
936 config->popularity = RXKB_POPULARITY_EXOTIC;
937 else
938 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
939 "xml:%u: invalid popularity attribute: expected "
940 "'standard' or 'exotic', got: '%s'\n",
941 ci->line, raw_popularity);
942 }
943 xmlFree(raw_popularity);
944
945 /* Note: this is only useful for options */
946 xmlChar *raw_layout_specific =
947 xmlGetProp(ci, (const xmlChar*)"layout-specific");
948 if (raw_layout_specific &&
949 xmlStrEqual(raw_layout_specific, (const xmlChar*)"true"))
950 config->layout_specific = true;
951 xmlFree(raw_layout_specific);
952
953 /* Process children */
954 for (node = ci->children; node; node = node->next) {
955 if (is_node(node, "name"))
956 config->name = extract_text(node);
957 else if (is_node(node, "description"))
958 config->description = extract_text(node);
959 else if (is_node(node, "shortDescription"))
960 config->brief = extract_text(node);
961 else if (is_node(node, "vendor"))
962 config->vendor = extract_text(node);
963 /* Note: the DTD allows for vendor + brief but models only use
964 * vendor and everything else only uses shortDescription */
965 }
966
967 if (!config->name || !strlen(config->name)) {
968 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
969 "xml:%u: missing required element 'name'\n",
970 ci->line);
971 config_item_free(config);
972 return false;
973 }
974
975 return true; /* only one configItem allowed in the dtd */
976 }
977 }
978
979 return false;
980 }
981
982 static void
983 parse_model(struct rxkb_context *ctx, xmlNode *model,
984 enum rxkb_popularity popularity)
985 {
986 struct config_item config = config_item_new(popularity);
987
988 if (parse_config_item(ctx, model, &config)) {
989 struct rxkb_model *m;
990
991 list_for_each(m, &ctx->models, base.link) {
992 if (streq(m->name, config.name)) {
993 config_item_free(&config);
994 return;
995 }
996 }
997
998 /* new model */
999 m = rxkb_model_create(&ctx->base);
1000 m->name = steal(&config.name);
1001 m->description = steal(&config.description);
1002 m->vendor = steal(&config.vendor);
1003 m->popularity = config.popularity;
1004 list_append(&ctx->models, &m->base.link);
1005 }
1006 }
1007
1008 static void
1009 parse_model_list(struct rxkb_context *ctx, xmlNode *model_list,
1010 enum rxkb_popularity popularity)
1011 {
1012 xmlNode *node = NULL;
1013
1014 for (node = model_list->children; node; node = node->next) {
1015 if (is_node(node, "model"))
1016 parse_model(ctx, node, popularity);
1017 }
1018 }
1019
1020 static void
1021 parse_language_list(xmlNode *language_list, struct rxkb_layout *layout)
1022 {
1023 xmlNode *node = NULL;
1024 struct rxkb_iso639_code *code;
1025
1026 for (node = language_list->children; node; node = node->next) {
1027 if (is_node(node, "iso639Id")) {
1028 char *str = extract_text(node);
1029 struct rxkb_object *parent;
1030
1031 if (!str || strlen(str) != 3) {
1032 free(str);
1033 continue;
1034 }
1035
1036 parent = &layout->base;
1037 code = rxkb_iso639_code_create(parent);
1038 code->code = str;
1039 list_append(&layout->iso639s, &code->base.link);
1040 }
1041 }
1042 }
1043
1044 static void
1045 parse_country_list(xmlNode *country_list, struct rxkb_layout *layout)
1046 {
1047 xmlNode *node = NULL;
1048 struct rxkb_iso3166_code *code;
1049
1050 for (node = country_list->children; node; node = node->next) {
1051 if (is_node(node, "iso3166Id")) {
1052 char *str = extract_text(node);
1053 struct rxkb_object *parent;
1054
1055 if (!str || strlen(str) != 2) {
1056 free(str);
1057 continue;
1058 }
1059
1060 parent = &layout->base;
1061 code = rxkb_iso3166_code_create(parent);
1062 code->code = str;
1063 list_append(&layout->iso3166s, &code->base.link);
1064 }
1065 }
1066 }
1067
1068 static void
1069 parse_variant(struct rxkb_context *ctx, struct rxkb_layout *l,
1070 xmlNode *variant, enum rxkb_popularity popularity)
1071 {
1072 xmlNode *ci;
1073 struct config_item config = config_item_new(popularity);
1074
1075 if (parse_config_item(ctx, variant, &config)) {
1076 struct rxkb_layout *v;
1077 bool exists = false;
1078
1079 list_for_each(v, &ctx->layouts, base.link) {
1080 if (streq_null(v->variant, config.name) &&
1081 streq(v->name, l->name)) {
1082 exists = true;
1083 break;
1084 }
1085 }
1086
1087 if (!exists) {
1088 v = rxkb_layout_create(&ctx->base);
1089 list_init(&v->iso639s);
1090 list_init(&v->iso3166s);
1091 v->name = strdup(l->name);
1092 v->variant = steal(&config.name);
1093 v->description = steal(&config.description);
1094 // if variant omits brief, inherit from parent layout.
1095 v->brief = config.brief == NULL ? strdup_safe(l->brief) : steal(&config.brief);
1096 v->popularity = config.popularity;
1097 list_append(&ctx->layouts, &v->base.link);
1098
1099 for (ci = variant->children; ci; ci = ci->next) {
1100 xmlNode *node;
1101
1102 if (!is_node(ci, "configItem"))
1103 continue;
1104
1105 bool found_language_list = false;
1106 bool found_country_list = false;
1107 for (node = ci->children; node; node = node->next) {
1108 if (is_node(node, "languageList")) {
1109 parse_language_list(node, v);
1110 found_language_list = true;
1111 }
1112 if (is_node(node, "countryList")) {
1113 parse_country_list(node, v);
1114 found_country_list = true;
1115 }
1116 }
1117 if (!found_language_list) {
1118 // inherit from parent layout
1119 struct rxkb_iso639_code* x;
1120 list_for_each(x, &l->iso639s, base.link) {
1121 struct rxkb_iso639_code* code = rxkb_iso639_code_create(&v->base);
1122 code->code = strdup(x->code);
1123 list_append(&v->iso639s, &code->base.link);
1124 }
1125 }
1126 if (!found_country_list) {
1127 // inherit from parent layout
1128 struct rxkb_iso3166_code* x;
1129 list_for_each(x, &l->iso3166s, base.link) {
1130 struct rxkb_iso3166_code* code = rxkb_iso3166_code_create(&v->base);
1131 code->code = strdup(x->code);
1132 list_append(&v->iso3166s, &code->base.link);
1133 }
1134 }
1135 }
1136 } else {
1137 config_item_free(&config);
1138 }
1139 }
1140 }
1141
1142 static void
1143 parse_variant_list(struct rxkb_context *ctx, struct rxkb_layout *l,
1144 xmlNode *variant_list, enum rxkb_popularity popularity)
1145 {
1146 xmlNode *node = NULL;
1147
1148 for (node = variant_list->children; node; node = node->next) {
1149 if (is_node(node, "variant"))
1150 parse_variant(ctx, l, node, popularity);
1151 }
1152 }
1153
1154 static void
1155 parse_layout(struct rxkb_context *ctx, xmlNode *layout,
1156 enum rxkb_popularity popularity)
1157 {
1158 struct config_item config = config_item_new(popularity);
1159 struct rxkb_layout *l;
1160 xmlNode *node = NULL;
1161 bool exists = false;
1162
1163 if (!parse_config_item(ctx, layout, &config))
1164 return;
1165
1166 list_for_each(l, &ctx->layouts, base.link) {
1167 if (streq(l->name, config.name) && l->variant == NULL) {
1168 exists = true;
1169 break;
1170 }
1171 }
1172
1173 if (!exists) {
1174 l = rxkb_layout_create(&ctx->base);
1175 list_init(&l->iso639s);
1176 list_init(&l->iso3166s);
1177 l->name = steal(&config.name);
1178 l->variant = NULL;
1179 l->description = steal(&config.description);
1180 l->brief = steal(&config.brief);
1181 l->popularity = config.popularity;
1182 list_append(&ctx->layouts, &l->base.link);
1183 } else {
1184 config_item_free(&config);
1185 }
1186
1187 for (node = layout->children; node; node = node->next) {
1188 if (is_node(node, "variantList")) {
1189 parse_variant_list(ctx, l, node, popularity);
1190 }
1191 if (!exists && is_node(node, "configItem")) {
1192 xmlNode *ll;
1193 for (ll = node->children; ll; ll = ll->next) {
1194 if (is_node(ll, "languageList"))
1195 parse_language_list(ll, l);
1196 if (is_node(ll, "countryList"))
1197 parse_country_list(ll, l);
1198 }
1199 }
1200 }
1201 }
1202
1203 static void
1204 parse_layout_list(struct rxkb_context *ctx, xmlNode *layout_list,
1205 enum rxkb_popularity popularity)
1206 {
1207 xmlNode *node = NULL;
1208
1209 for (node = layout_list->children; node; node = node->next) {
1210 if (is_node(node, "layout"))
1211 parse_layout(ctx, node, popularity);
1212 }
1213 }
1214
1215 static void
1216 parse_option(struct rxkb_context *ctx, struct rxkb_option_group *group,
1217 xmlNode *option, enum rxkb_popularity popularity)
1218 {
1219 struct config_item config = config_item_new(popularity);
1220
1221 if (parse_config_item(ctx, option, &config)) {
1222 struct rxkb_option *o;
1223
1224 list_for_each(o, &group->options, base.link) {
1225 if (streq(o->name, config.name)) {
1226 config_item_free(&config);
1227 return;
1228 }
1229 }
1230
1231 o = rxkb_option_create(&group->base);
1232 o->name = steal(&config.name);
1233 o->description = steal(&config.description);
1234 o->popularity = config.popularity;
1235 o->layout_specific = config.layout_specific;
1236 list_append(&group->options, &o->base.link);
1237 }
1238 }
1239
1240 static void
1241 parse_group(struct rxkb_context *ctx, xmlNode *group,
1242 enum rxkb_popularity popularity)
1243 {
1244 struct config_item config = config_item_new(popularity);
1245 struct rxkb_option_group *g;
1246 xmlNode *node = NULL;
1247 xmlChar *multiple;
1248 bool exists = false;
1249
1250 if (!parse_config_item(ctx, group, &config))
1251 return;
1252
1253 list_for_each(g, &ctx->option_groups, base.link) {
1254 if (streq(g->name, config.name)) {
1255 exists = true;
1256 break;
1257 }
1258 }
1259
1260 if (!exists) {
1261 g = rxkb_option_group_create(&ctx->base);
1262 g->name = steal(&config.name);
1263 g->description = steal(&config.description);
1264 g->popularity = config.popularity;
1265
1266 multiple = xmlGetProp(group, (const xmlChar*)"allowMultipleSelection");
1267 if (multiple && xmlStrEqual(multiple, (const xmlChar*)"true"))
1268 g->allow_multiple = true;
1269 xmlFree(multiple);
1270
1271 list_init(&g->options);
1272 list_append(&ctx->option_groups, &g->base.link);
1273 } else {
1274 config_item_free(&config);
1275 }
1276
1277 for (node = group->children; node; node = node->next) {
1278 if (is_node(node, "option"))
1279 parse_option(ctx, g, node, popularity);
1280 }
1281 }
1282
1283 static void
1284 parse_option_list(struct rxkb_context *ctx, xmlNode *option_list,
1285 enum rxkb_popularity popularity)
1286 {
1287 xmlNode *node = NULL;
1288
1289 for (node = option_list->children; node; node = node->next) {
1290 if (is_node(node, "group"))
1291 parse_group(ctx, node, popularity);
1292 }
1293 }
1294
1295 static void
1296 parse_rules_xml(struct rxkb_context *ctx, xmlNode *root,
1297 enum rxkb_popularity popularity)
1298 {
1299 xmlNode *node = NULL;
1300
1301 for (node = root->children; node; node = node->next) {
1302 if (is_node(node, "modelList"))
1303 parse_model_list(ctx, node, popularity);
1304 else if (is_node(node, "layoutList"))
1305 parse_layout_list(ctx, node, popularity);
1306 else if (is_node(node, "optionList"))
1307 parse_option_list(ctx, node, popularity);
1308 }
1309 }
1310
1311 static void
1312 ATTR_PRINTF(2, 0)
1313 xml_error_func(void *ctx, const char *msg, ...)
1314 {
1315 static char buf[PATH_MAX];
1316 static int slen = 0;
1317 va_list args;
1318 int rc;
1319
1320 /* libxml2 prints IO errors from bad includes paths by
1321 * calling the error function once per word. So we get to
1322 * re-assemble the message here and print it when we get
1323 * the line break. My enthusiasm about this is indescribable.
1324 */
1325 va_start(args, msg);
1326 rc = vsnprintf(&buf[slen], sizeof(buf) - slen, msg, args);
1327 va_end(args);
1328
1329 /* This shouldn't really happen */
1330 if (rc < 0) {
1331 log_err(ctx, XKB_ERROR_INSUFFICIENT_BUFFER_SIZE,
1332 "+++ out of cheese error. redo from start +++\n");
1333 slen = 0;
1334 memset(buf, 0, sizeof(buf));
1335 return;
1336 }
1337
1338 slen += rc;
1339 if (slen >= (int)sizeof(buf)) {
1340 /* truncated, let's flush this */
1341 buf[sizeof(buf) - 1] = '\n';
1342 slen = sizeof(buf);
1343 }
1344
1345 /* We're assuming here that the last character is \n. */
1346 if (buf[slen - 1] == '\n') {
1347 log_err(ctx, XKB_LOG_MESSAGE_NO_ID, "%s", buf);
1348 memset(buf, 0, sizeof(buf));
1349 slen = 0;
1350 }
1351 }
1352
1353 #ifdef HAVE_XML_CTXT_SET_ERRORHANDLER
1354 static void
1355 xml_structured_error_func(void *userData, const xmlError * error)
1356 {
1357 xmlFormatError(error, xml_error_func, userData);
1358 }
1359 #endif
1360
1361 #ifdef XML_PARSE_NO_XXE
1362 #define _XML_OPTIONS (XML_PARSE_NONET | XML_PARSE_NOENT | XML_PARSE_NO_XXE)
1363 #else
1364 #define _XML_OPTIONS (XML_PARSE_NONET)
1365 #endif
1366
1367 static bool
1368 validate(struct rxkb_context *ctx, xmlDoc *doc)
1369 {
1370 bool success = false;
1371 /* This is a modified version of the xkeyboard-config xkb.dtd:
1372 * • xkeyboard-config requires modelList, layoutList and optionList,
1373 * but we allow for any of those to be missing.
1374 * • xkeyboard-config sets default value of “popularity” to “standard”,
1375 * but we set this value depending if we are currently parsing an
1376 * “extras” rule file.
1377 */
1378 const char dtdstr[] =
1379 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1380 "<!ELEMENT xkbConfigRegistry (modelList?, layoutList?, optionList?)>\n"
1381 "<!ATTLIST xkbConfigRegistry version CDATA \"1.1\">\n"
1382 "<!ELEMENT modelList (model*)>\n"
1383 "<!ELEMENT model (configItem)>\n"
1384 "<!ELEMENT layoutList (layout*)>\n"
1385 "<!ELEMENT layout (configItem, variantList?)>\n"
1386 "<!ELEMENT optionList (group*)>\n"
1387 "<!ELEMENT variantList (variant*)>\n"
1388 "<!ELEMENT variant (configItem)>\n"
1389 "<!ELEMENT group (configItem, option*)>\n"
1390 "<!ATTLIST group allowMultipleSelection (true|false) \"false\">\n"
1391 "<!ELEMENT option (configItem)>\n"
1392 "<!ELEMENT configItem (name, shortDescription?, description?, vendor?, countryList?, languageList?, hwList?)>\n"
1393 "<!ATTLIST configItem layout-specific (true|false) \"false\">\n"
1394 "<!ATTLIST configItem popularity (standard|exotic) #IMPLIED>\n"
1395 "<!ELEMENT name (#PCDATA)>\n"
1396 "<!ELEMENT shortDescription (#PCDATA)>\n"
1397 "<!ELEMENT description (#PCDATA)>\n"
1398 "<!ELEMENT vendor (#PCDATA)>\n"
1399 "<!ELEMENT countryList (iso3166Id+)>\n"
1400 "<!ELEMENT iso3166Id (#PCDATA)>\n"
1401 "<!ELEMENT languageList (iso639Id+)>\n"
1402 "<!ELEMENT iso639Id (#PCDATA)>\n"
1403 "<!ELEMENT hwList (hwId+)>\n"
1404 "<!ELEMENT hwId (#PCDATA)>\n";
1405
1406 #ifdef HAVE_XML_CTXT_PARSE_DTD
1407 /* Use safer function with context if available, and set
1408 * the contextual error handler. */
1409 xmlParserCtxtPtr xmlCtxt = xmlNewParserCtxt();
1410 if (!xmlCtxt)
1411 return false;
1412 xmlCtxtSetErrorHandler(xmlCtxt, xml_structured_error_func, ctx);
1413 xmlCtxtSetOptions(xmlCtxt, _XML_OPTIONS | XML_PARSE_DTDLOAD);
1414
1415 xmlParserInputPtr pinput =
1416 xmlNewInputFromMemory(NULL, dtdstr, ARRAY_SIZE(dtdstr) - 1,
1417 XML_INPUT_BUF_STATIC);
1418 if (!pinput)
1419 goto dtd_error;
1420
1421 xmlDtd *dtd = xmlCtxtParseDtd(xmlCtxt, pinput, NULL, NULL);
1422 #else
1423 /* Note: do not use xmlParserInputBufferCreateStatic, it generates random
1424 * DTD validity errors for unknown reasons */
1425 xmlParserInputBufferPtr buf =
1426 xmlParserInputBufferCreateMem(dtdstr, ARRAY_SIZE(dtdstr) - 1,
1427 XML_CHAR_ENCODING_NONE);
1428 if (!buf)
1429 goto dtd_error;
1430 xmlDtd *dtd = xmlIOParseDTD(NULL, buf, XML_CHAR_ENCODING_UTF8);
1431 #endif
1432
1433 if (!dtd) {
1434 log_err(ctx, XKB_LOG_MESSAGE_NO_ID, "Failed to load DTD\n");
1435 goto dtd_error;
1436 }
1437
1438 #ifdef HAVE_XML_CTXT_PARSE_DTD
1439 success = xmlCtxtValidateDtd(xmlCtxt, doc, dtd);
1440 #else
1441 xmlValidCtxt *dtdvalid = xmlNewValidCtxt();
1442 success = xmlValidateDtd(dtdvalid, doc, dtd);
1443 if (dtdvalid)
1444 xmlFreeValidCtxt(dtdvalid);
1445 #endif
1446
1447 xmlFreeDtd(dtd);
1448
1449 dtd_error:
1450 #ifdef HAVE_XML_CTXT_PARSE_DTD
1451 xmlFreeParserCtxt(xmlCtxt);
1452 #endif
1453 return success;
1454 }
1455
1456 static bool
1457 parse(struct rxkb_context *ctx, const char *path,
1458 enum rxkb_popularity popularity)
1459 {
1460 bool success = false;
1461 xmlDoc *doc = NULL;
1462 xmlNode *root = NULL;
1463
1464 if (!check_eaccess(path, R_OK))
1465 return false;
1466
1467 LIBXML_TEST_VERSION
1468
1469 xmlParserCtxtPtr xmlCtxt = xmlNewParserCtxt();
1470 if (!xmlCtxt)
1471 return false;
1472
1473 #ifdef XML_PARSE_NO_XXE
1474 #define _XML_OPTIONS (XML_PARSE_NONET | XML_PARSE_NOENT | XML_PARSE_NO_XXE)
1475 #else
1476 #define _XML_OPTIONS (XML_PARSE_NONET)
1477 #endif
1478 xmlCtxtUseOptions(xmlCtxt, _XML_OPTIONS);
1479
1480 #ifdef HAVE_XML_CTXT_SET_ERRORHANDLER
1481 /* Prefer contextual handler whenever possible. It takes precedence over
1482 * the global generic handler. */
1483 xmlCtxtSetErrorHandler(xmlCtxt, xml_structured_error_func, ctx);
1484 #endif
1485 #ifndef HAVE_XML_CTXT_PARSE_DTD
1486 /* This is needed for the DTD validation */
1487 xmlSetGenericErrorFunc(ctx, xml_error_func);
1488 #endif
1489
1490 doc = xmlCtxtReadFile(xmlCtxt, path, NULL, 0);
1491 if (!doc)
1492 goto parse_error;
1493
1494 if (!validate(ctx, doc)) {
1495 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
1496 "XML error: failed to validate document at %s\n", path);
1497 goto validate_error;
1498 }
1499
1500 root = xmlDocGetRootElement(doc);
1501 parse_rules_xml(ctx, root, popularity);
1502
1503 success = true;
1504 validate_error:
1505 xmlFreeDoc(doc);
1506 parse_error:
1507
1508 #ifndef HAVE_XML_CTXT_PARSE_DTD
1509 /*
1510 * Reset the default libxml2 error handler to default, because this handler
1511 * is global and may be used on an invalid rxkb_context, e.g. *after* the
1512 * following sequence:
1513 *
1514 * rxkb_context_new();
1515 * rxkb_context_parse();
1516 * rxkb_context_unref();
1517 */
1518 xmlSetGenericErrorFunc(NULL, NULL);
1519 #endif
1520 #ifdef HAVE_XML_CTXT_SET_ERRORHANDLER
1521 xmlCtxtSetErrorHandler(xmlCtxt, NULL, NULL);
1522 #endif
1523 xmlFreeParserCtxt(xmlCtxt);
1524
1525 return success;
1526 }