aboutsummaryrefslogtreecommitdiff
blob: efc4a8bb7ee167e613a6585f5e8e0bc76294e217 (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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
/*
  Copyright 2012 Alexandre Rostovtsev

  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, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <limits.h>
#include <stdlib.h>
#include <string.h>

#include <dbus/dbus-protocol.h>
#include <glib.h>
#include <gio/gio.h>

#include "localed.h"
#include "locale1-generated.h"
#include "main.h"
#include "utils.h"

#include "config.h"

#define SERVICE_NAME "openrc-settingsd localed"

static guint bus_id = 0;
static gboolean read_only = FALSE;

static OpenrcSettingsdLocaledLocale1 *locale1 = NULL;

static gchar *locale_variables[] = {
    "LANG", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_MESSAGES", "LC_PAPER", "LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT", "LC_IDENTIFICATION", NULL
};

static gchar **locale = NULL; /* Expected format is { "LANG=foo", "LC_TIME=bar", NULL } */
static GFile *locale_file = NULL;
G_LOCK_DEFINE_STATIC (locale);

static gchar *vconsole_keymap = NULL;
static gchar *vconsole_keymap_toggle = NULL;
static GFile *keymaps_file = NULL;
G_LOCK_DEFINE_STATIC (keymaps);

static gchar *x11_layout = NULL;
static gchar *x11_model = NULL;
static gchar *x11_variant = NULL;
static gchar *x11_options = NULL;
static GFile *x11_gentoo_file = NULL;
static GFile *x11_systemd_file = NULL;
G_LOCK_DEFINE_STATIC (xorg_conf);

/* keyboard model map file parser */

static GFile *kbd_model_map_file = NULL;

GRegex *kbd_model_map_line_comment_re = NULL;
GRegex *kbd_model_map_line_re = NULL;

struct kbd_model_map_entry {
    gchar *vconsole_keymap;
    gchar *x11_layout;
    gchar *x11_model;
    gchar *x11_variant;
    gchar *x11_options;
};

static void
kbd_model_map_regex_destroy ()
{
    if (kbd_model_map_line_comment_re != NULL) {
        g_regex_unref (kbd_model_map_line_comment_re);
        kbd_model_map_line_comment_re = NULL;
    }
    if (kbd_model_map_line_re != NULL) {
        g_regex_unref (kbd_model_map_line_re);
        kbd_model_map_line_re = NULL;
    }
}

static void
kbd_model_map_regex_init ()
{
    if (kbd_model_map_line_comment_re == NULL) {
        kbd_model_map_line_comment_re = g_regex_new ("^\\s*(?:#.*)?$", G_REGEX_ANCHORED, 0, NULL);
        g_assert (kbd_model_map_line_comment_re != NULL);
    }
    if (kbd_model_map_line_re == NULL) {
        kbd_model_map_line_re = g_regex_new ("^\\s*(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)", G_REGEX_ANCHORED, 0, NULL);
        g_assert (kbd_model_map_line_re != NULL);
    }
}

static gboolean
kbd_model_map_entry_matches_vconsole (const struct kbd_model_map_entry *entry,
                                      const gchar *vconsole_keymap)
{
    return !g_strcmp0 (vconsole_keymap, entry->vconsole_keymap);
}

static gboolean
matches_delimeted (const gchar *left,
                   const gchar *right,
                   const gchar *delimeter,
                   unsigned int *failure_score)
{
    gboolean ret = FALSE;
    gchar **leftv = NULL, **rightv = NULL;
    gchar **leftcur = NULL, **rightcur = NULL;

    if (left == NULL || left[0] == 0)
        leftv = g_new0 (gchar *, 1);
    else
        leftv = g_strsplit (left, delimeter, 0);

    if (right == NULL || right[0] == 0)
        rightv = g_new0 (gchar *, 1);
    else
        rightv = g_strsplit (right, delimeter, 0);

    if (failure_score != NULL)
        *failure_score = 0;

    for (leftcur = leftv; *leftcur != NULL; leftcur++) {
        gboolean found = FALSE;
        for (rightcur = rightv; *rightcur != NULL; rightcur++)
            if (!g_strcmp0 (*leftcur, *rightcur)) {
                found = TRUE;
                break;
            }
        if (found)
            ret = TRUE;
        else if (failure_score != NULL)
            (*failure_score)++;
    }

    for (rightcur = rightv; *rightcur != NULL; rightcur++) {
        gboolean found = FALSE;
        for (leftcur = leftv; *leftcur != NULL; leftcur++)
            if (!g_strcmp0 (*rightcur, *leftcur)) {
                found = TRUE;
                break;
            }
        if (found)
            ret = TRUE;
        else if (failure_score != NULL)
            (*failure_score)++;
    }

    g_strfreev (leftv);
    g_strfreev (rightv);
    return ret;
}

static gboolean
kbd_model_map_entry_matches_x11 (const struct kbd_model_map_entry *entry,
                                 const gchar *_x11_layout,
                                 const gchar *_x11_model,
                                 const gchar *_x11_variant,
                                 const gchar *_x11_options,
                                 unsigned int *failure_score)
{
    unsigned int x11_layout_failures;
    gboolean ret = FALSE;

    ret = matches_delimeted (_x11_layout, entry->x11_layout, ",", &x11_layout_failures);
    if (failure_score != NULL)
        *failure_score = 10000 * !ret +
                         100 * x11_layout_failures +
                         (g_strcmp0 (_x11_model, entry->x11_model) ? 1 : 0) +
                         10 * (g_strcmp0 (_x11_variant, entry->x11_variant) ? 1 : 0) +
                         !matches_delimeted (_x11_options, entry->x11_options, ",", NULL);
    return ret;
}

static void
kbd_model_map_entry_free (struct kbd_model_map_entry *entry)
{
    if (entry == NULL)
        return;

    g_free (entry->vconsole_keymap);
    g_free (entry->x11_layout);
    g_free (entry->x11_model);
    g_free (entry->x11_variant);
    g_free (entry->x11_options);

    g_free (entry);
}

static GList*
kbd_model_map_load (GError **error)
{
    GList *ret = NULL;
    gchar *filename = NULL, *filebuf = NULL, *line = NULL, *newline = NULL;
    struct kbd_model_map_entry *entry = NULL;

    filename = g_file_get_path (kbd_model_map_file);
    g_debug ("Parsing keyboard model map file file: '%s'", filename);

    if (!g_file_load_contents (kbd_model_map_file, NULL, &filebuf, NULL, NULL, error)) {
        g_prefix_error (error, "Unable to read '%s':", filename);
        goto out;
    }

    for (line = filebuf; *line != 0; line = newline + 1) {
        struct kbd_model_map_entry *entry = NULL;
        GMatchInfo *match_info = NULL;
        gboolean m = FALSE;

        if ((newline = strstr (line, "\n")) != NULL)
            *newline = 0;
        else
            newline = line + strlen (line) - 1;

        m = g_regex_match (kbd_model_map_line_comment_re, line, 0, &match_info);
        _g_match_info_clear (&match_info);
        if (m)
            continue;

        if (!g_regex_match (kbd_model_map_line_re, line,  0, &match_info)) {
            g_propagate_error (error,
                               g_error_new (G_FILE_ERROR, G_FILE_ERROR_FAILED,
                                            "Failed to parse line '%s' in '%s'", line, filename));
            g_match_info_free (match_info);
            if (ret != NULL) {
                g_list_free_full (ret, (GDestroyNotify)kbd_model_map_entry_free);
                ret = NULL;
            }
            goto out;
        }
        entry = g_new0 (struct kbd_model_map_entry, 1);
        entry->vconsole_keymap = g_match_info_fetch (match_info, 1);
        entry->x11_layout = g_match_info_fetch (match_info, 2);
        entry->x11_model = g_match_info_fetch (match_info, 3);
        entry->x11_variant = g_match_info_fetch (match_info, 4);
        entry->x11_options = g_match_info_fetch (match_info, 5);

        // "-" in the map file stands for an empty string
        if (!g_strcmp0 (entry->x11_model, "-"))
            entry->x11_model[0] = 0;
        if (!g_strcmp0 (entry->x11_variant, "-"))
            entry->x11_variant[0] = 0;
        if (!g_strcmp0 (entry->x11_options, "-"))
            entry->x11_options[0] = 0;

        ret = g_list_prepend (ret, entry);
        _g_match_info_clear (&match_info);
    }
  out:
    if (ret != NULL)
        ret = g_list_reverse (ret);

    g_free (filename);
    g_free (filebuf);
    return ret;
}

/* Trivial /etc/X11/xorg.conf.d/30-keyboard.conf parser */

enum XORG_CONFD_LINE_TYPE {
    XORG_CONFD_LINE_TYPE_UNKNOWN,
    XORG_CONFD_LINE_TYPE_COMMENT,
    XORG_CONFD_LINE_TYPE_SECTION_INPUT_CLASS,
    XORG_CONFD_LINE_TYPE_SECTION_OTHER,
    XORG_CONFD_LINE_TYPE_END_SECTION,
    XORG_CONFD_LINE_TYPE_MATCH_IS_KEYBOARD,
    XORG_CONFD_LINE_TYPE_XKB_LAYOUT,
    XORG_CONFD_LINE_TYPE_XKB_MODEL,
    XORG_CONFD_LINE_TYPE_XKB_VARIANT,
    XORG_CONFD_LINE_TYPE_XKB_OPTIONS,
};

GRegex *xorg_confd_line_comment_re = NULL;
GRegex *xorg_confd_line_section_input_class_re = NULL;
GRegex *xorg_confd_line_section_re = NULL;
GRegex *xorg_confd_line_end_section_re = NULL;
GRegex *xorg_confd_line_match_is_keyboard_re = NULL;
GRegex *xorg_confd_line_xkb_layout_re = NULL;
GRegex *xorg_confd_line_xkb_model_re = NULL;
GRegex *xorg_confd_line_xkb_variant_re = NULL;
GRegex *xorg_confd_line_xkb_options_re = NULL;

struct xorg_confd_line_entry {
    gchar *string;
    gchar *value; /* for one of the options we are interested in */
    enum XORG_CONFD_LINE_TYPE type;
};

struct xorg_confd_parser {
    GFile *file;
    gchar *filename;
    GList *line_list;
    GList *section; /* start of relevant InputClass section */
};

static void
xorg_confd_regex_destroy ()
{
    if (xorg_confd_line_comment_re != NULL) {
        g_regex_unref (xorg_confd_line_comment_re);
        xorg_confd_line_comment_re = NULL;
    }
    if (xorg_confd_line_section_input_class_re != NULL) {
        g_regex_unref (xorg_confd_line_section_input_class_re);
        xorg_confd_line_section_input_class_re = NULL;
    }
    if (xorg_confd_line_section_re != NULL) {
        g_regex_unref (xorg_confd_line_section_re);
        xorg_confd_line_section_re = NULL;
    }
    if (xorg_confd_line_end_section_re != NULL) {
        g_regex_unref (xorg_confd_line_end_section_re);
        xorg_confd_line_end_section_re = NULL;
    }
    if (xorg_confd_line_match_is_keyboard_re != NULL) {
        g_regex_unref (xorg_confd_line_match_is_keyboard_re);
        xorg_confd_line_match_is_keyboard_re = NULL;
    }
    if (xorg_confd_line_xkb_layout_re != NULL) {
        g_regex_unref (xorg_confd_line_xkb_layout_re);
        xorg_confd_line_xkb_layout_re = NULL;
    }
    if (xorg_confd_line_xkb_model_re != NULL) {
        g_regex_unref (xorg_confd_line_xkb_model_re);
        xorg_confd_line_xkb_model_re = NULL;
    }
    if (xorg_confd_line_xkb_variant_re != NULL) {
        g_regex_unref (xorg_confd_line_xkb_variant_re);
        xorg_confd_line_xkb_variant_re = NULL;
    }
    if (xorg_confd_line_xkb_options_re != NULL) {
        g_regex_unref (xorg_confd_line_xkb_options_re);
        xorg_confd_line_xkb_options_re = NULL;
    }
}

static void
xorg_confd_regex_init ()
{
    if (xorg_confd_line_comment_re == NULL) {
        xorg_confd_line_comment_re = g_regex_new ("^\\s*#", G_REGEX_ANCHORED, 0, NULL);
        g_assert (xorg_confd_line_comment_re != NULL);
    }
    if (xorg_confd_line_section_input_class_re == NULL) {
        xorg_confd_line_section_input_class_re = g_regex_new ("^\\s*Section\\s+\"InputClass\"", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_section_input_class_re != NULL);
    }
    if (xorg_confd_line_section_re == NULL) {
        xorg_confd_line_section_re = g_regex_new ("^\\s*Section\\s+\"([^\"])\"", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_section_re != NULL);
    }
    if (xorg_confd_line_end_section_re == NULL) {
        xorg_confd_line_end_section_re = g_regex_new ("^\\s*EndSection", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_end_section_re != NULL);
    }
    if (xorg_confd_line_match_is_keyboard_re == NULL) {
        xorg_confd_line_match_is_keyboard_re = g_regex_new ("^\\s*MatchIsKeyboard(?:\\s*$|\\s+\"(?:1|on|true|yes)\")", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_match_is_keyboard_re != NULL);
    }
    if (xorg_confd_line_xkb_layout_re == NULL) {
        xorg_confd_line_xkb_layout_re = g_regex_new ("^(\\s*Option\\s+\"XkbLayout\"\\s+)\"([^\"]*)\"", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_xkb_layout_re != NULL);
    }
    if (xorg_confd_line_xkb_model_re == NULL) {
        xorg_confd_line_xkb_model_re = g_regex_new ("^(\\s*Option\\s+\"XkbModel\"\\s+)\"([^\"]*)\"", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_xkb_model_re != NULL);
    }
    if (xorg_confd_line_xkb_variant_re == NULL) {
        xorg_confd_line_xkb_variant_re = g_regex_new ("^(\\s*Option\\s+\"XkbVariant\"\\s+)\"([^\"]*)\"", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_xkb_variant_re != NULL);
    }
    if (xorg_confd_line_xkb_options_re == NULL) {
        xorg_confd_line_xkb_options_re = g_regex_new ("^(\\s*Option\\s+\"XkbOptions\"\\s+)\"([^\"]*)\"", G_REGEX_ANCHORED|G_REGEX_CASELESS, 0, NULL);
        g_assert (xorg_confd_line_xkb_options_re != NULL);
    }
}

static void
xorg_confd_line_entry_free (struct xorg_confd_line_entry *entry)
{
    if (entry == NULL)
        return;

    g_free (entry->string);
    g_free (entry->value);

    g_free (entry);
}

static struct xorg_confd_line_entry *
xorg_confd_line_entry_new (const gchar *string,
                           const gchar *value,
                           enum XORG_CONFD_LINE_TYPE type)
{
    struct xorg_confd_line_entry *entry;

    entry = g_new0 (struct xorg_confd_line_entry, 1);
    entry->string = g_strdup (string);
    entry->value = g_strdup (value);
    entry->type = type;
    return entry;
}

static void
xorg_confd_parser_free (struct xorg_confd_parser *parser)
{
    if (parser == NULL)
        return;

    if (parser->file != NULL)
        g_object_unref (parser->file);

    g_free (parser->filename);

    if (parser->line_list != NULL)
        g_list_free_full (parser->line_list, (GDestroyNotify)xorg_confd_line_entry_free);

    g_free (parser);
}

static struct xorg_confd_parser *
xorg_confd_parser_new (GFile *xorg_confd_file,
                       GError **error)
{
    struct xorg_confd_parser *parser = NULL;
    gchar *filebuf = NULL, *line = NULL, *newline = NULL;
    GList *input_class_section_start = NULL;
    gboolean in_section = FALSE, in_xkb_section = FALSE;

    if (xorg_confd_file == NULL)
        return NULL;

    parser = g_new0 (struct xorg_confd_parser, 1);
    parser->file = g_object_ref (xorg_confd_file);
    parser->filename = g_file_get_path (xorg_confd_file);
    g_debug ("Parsing xorg.conf.d file: '%s'", parser->filename);
    if (!g_file_load_contents (xorg_confd_file, NULL, &filebuf, NULL, NULL, error)) {
        g_prefix_error (error, "Unable to read '%s':", parser->filename);
        goto fail;
    }

    for (line = filebuf; *line != 0; line = newline + 1) {
        struct xorg_confd_line_entry *entry = NULL;
        GMatchInfo *match_info = NULL;
        gboolean matched = FALSE;
        gboolean m = FALSE;

        if ((newline = strstr (line, "\n")) != NULL)
            *newline = 0;
        else
            newline = line + strlen (line) - 1;

        entry = xorg_confd_line_entry_new (line, NULL, XORG_CONFD_LINE_TYPE_UNKNOWN);

        if (g_regex_match (xorg_confd_line_comment_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as comment", line);
            entry->type = XORG_CONFD_LINE_TYPE_COMMENT;
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_section_input_class_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as InputClass section", line);
            if (in_section)
                goto no_match;
            in_section = TRUE;
            entry->type = XORG_CONFD_LINE_TYPE_SECTION_INPUT_CLASS;
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_section_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as non-InputClass section", line);
            if (in_section)
                goto no_match;
            in_section = TRUE;
            entry->type = XORG_CONFD_LINE_TYPE_SECTION_OTHER;
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_end_section_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as end of section", line);
            if (!in_section)
                goto no_match;
            entry->type = XORG_CONFD_LINE_TYPE_END_SECTION;
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_match_is_keyboard_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as MatchIsKeyboard declaration", line);
            if (!in_section)
                goto no_match;
            entry->type = XORG_CONFD_LINE_TYPE_MATCH_IS_KEYBOARD;
            in_xkb_section = TRUE;
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_xkb_layout_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as XkbLayout option", line);
            if (!in_section)
                goto no_match;
            entry->type = XORG_CONFD_LINE_TYPE_XKB_LAYOUT;
            entry->value = g_match_info_fetch (match_info, 2);
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_xkb_model_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as XkbModel option", line);
            if (!in_section)
                goto no_match;
            entry->type = XORG_CONFD_LINE_TYPE_XKB_MODEL;
            entry->value = g_match_info_fetch (match_info, 2);
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_xkb_variant_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as XkbVariant option", line);
            if (!in_section)
                goto no_match;
            entry->type = XORG_CONFD_LINE_TYPE_XKB_VARIANT;
            entry->value = g_match_info_fetch (match_info, 2);
        } else if (_g_match_info_clear (&match_info) && g_regex_match (xorg_confd_line_xkb_options_re, line, 0, &match_info)) {
            g_debug ("Parsed line '%s' as XkbOptions option", line);
            if (!in_section)
                goto no_match;
            entry->type = XORG_CONFD_LINE_TYPE_XKB_OPTIONS;
            entry->value = g_match_info_fetch (match_info, 2);
        }

        if (entry->type == XORG_CONFD_LINE_TYPE_UNKNOWN)
            g_debug ("Parsing line '%s' as unknown", line);

        _g_match_info_clear (&match_info);
        parser->line_list = g_list_prepend (parser->line_list, entry);
        if (in_section) {
            if (entry->type == XORG_CONFD_LINE_TYPE_SECTION_INPUT_CLASS)
                input_class_section_start = parser->line_list;
            else if (entry->type == XORG_CONFD_LINE_TYPE_END_SECTION) {
                if (in_xkb_section)
                    parser->section = input_class_section_start;

                input_class_section_start = NULL;
                in_section = FALSE;
                in_xkb_section = FALSE;
            }
        }
        continue;

  no_match:
        /* Nothing matched... */
        g_free (entry);
        _g_match_info_clear (&match_info);
        goto parse_fail;
    }

    if (in_section) {
        /* Unterminated section */
        goto parse_fail;
    }

    parser->line_list = g_list_reverse (parser->line_list);

  out:
    g_free (filebuf);
    return parser;

  parse_fail:
    g_propagate_error (error,
                       g_error_new (G_FILE_ERROR, G_FILE_ERROR_FAILED,
                                   "Unable to parse '%s'", parser->filename));
  fail:
    g_free (filebuf);
    xorg_confd_parser_free (parser);
    return NULL;
}

static void
xorg_confd_parser_get_xkb (const struct xorg_confd_parser *parser,
                           gchar **layout_p,
                           gchar **model_p,
                           gchar **variant_p,
                           gchar **options_p)
{
    GList *curr = NULL;
    gchar *layout = NULL, *model = NULL, *variant = NULL, *options = NULL;

    if (parser == NULL)
        return;
    for (curr = parser->section; curr != NULL; curr = curr->next) {
        GMatchInfo *match_info = NULL;
        struct xorg_confd_line_entry *entry = (struct xorg_confd_line_entry *) curr->data;

        if (entry->type == XORG_CONFD_LINE_TYPE_END_SECTION)
            break;
        else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_LAYOUT)
            layout = entry->value;
        else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_MODEL)
            model = entry->value;
        else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_VARIANT)
            variant = entry->value;
        else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_OPTIONS)
            options = entry->value;
    }
    *layout_p = g_strdup (layout);
    *model_p = g_strdup (model);
    *variant_p = g_strdup (variant);
    *options_p = g_strdup (options);
}

static GList *
xorg_confd_parser_line_set_or_delete (GList *line,
                                      const gchar *value,
                                      const GRegex *re)
{
    gchar *replacement = NULL, *replaced = NULL;

    g_assert (line != NULL);

    struct xorg_confd_line_entry *entry = (struct xorg_confd_line_entry *) line->data;

    if (value == NULL || !g_strcmp0 (value, "")) {
        /* If value is null, we delete the line and return previous one */
        g_debug ("Deleting entry '%s'", entry->string);
        GList *prev, *next;

        prev = line->prev;
        next = line->next;
        line->prev = NULL;
        line->next = NULL;
        g_list_free_full (line, (GDestroyNotify)xorg_confd_line_entry_free);
        if (prev != NULL)
            prev->next = next;
        if (next != NULL)
            next->prev = prev;
        return prev;
    }
    g_free (entry->value);
    entry->value = g_strdup (value);
    replacement = g_strdup_printf ("\\1\"%s\"", value);
    replaced = g_regex_replace (re, entry->string, -1, 0, replacement, 0, NULL);
    g_debug ("Setting entry '%s' to new value '%s' i.e. '%s'", entry->string, value, replaced);
    g_free (replacement);
    g_free (entry->string);
    entry->string = replaced;

    return line;
}

static void
xorg_confd_parser_set_xkb (struct xorg_confd_parser *parser,
                           const gchar *layout,
                           const gchar *model,
                           const gchar *variant,
                           const gchar *options)
{
    GList *curr = NULL, *end = NULL;
    gboolean layout_found = FALSE, model_found = FALSE, variant_found = FALSE, options_found = FALSE;
    struct xorg_confd_line_entry *entry = NULL;
    gchar *string = NULL;

    if (parser == NULL)
        return;

    if (parser->section == NULL) {
        GList *section = NULL;

        entry = xorg_confd_line_entry_new ("Section \"InputClass\"", NULL, XORG_CONFD_LINE_TYPE_SECTION_INPUT_CLASS);
        section = g_list_prepend (section, entry);

        entry = xorg_confd_line_entry_new ("        Identifier \"keyboard-all\"", NULL, XORG_CONFD_LINE_TYPE_UNKNOWN);
        section = g_list_prepend (section, entry);

        entry = entry = xorg_confd_line_entry_new ("        MatchIsKeyboard \"on\"", NULL, XORG_CONFD_LINE_TYPE_MATCH_IS_KEYBOARD);
        section = g_list_prepend (section, entry);

        entry = entry = xorg_confd_line_entry_new ("EndSection", NULL, XORG_CONFD_LINE_TYPE_END_SECTION);
        section = g_list_prepend (section, entry);

        section = g_list_reverse (section);
        parser->section = section;
        parser->line_list = g_list_concat (parser->line_list, section);
    }

    for (curr = parser->section; curr != NULL; curr = curr->next) {
        entry = (struct xorg_confd_line_entry *) curr->data;

        if (entry->type == XORG_CONFD_LINE_TYPE_END_SECTION) {
            end = curr;
            break;
        } else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_LAYOUT) {
            layout_found = TRUE;
            curr = xorg_confd_parser_line_set_or_delete (curr, layout, xorg_confd_line_xkb_layout_re);
        } else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_MODEL) {
            model_found = TRUE;
            curr = xorg_confd_parser_line_set_or_delete (curr, model, xorg_confd_line_xkb_model_re);
        } else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_VARIANT) {
            variant_found = TRUE;
            curr = xorg_confd_parser_line_set_or_delete (curr, variant, xorg_confd_line_xkb_variant_re);
        } else if (entry->type == XORG_CONFD_LINE_TYPE_XKB_OPTIONS) {
            options_found = TRUE;
            curr = xorg_confd_parser_line_set_or_delete (curr, options, xorg_confd_line_xkb_options_re);
        }
    }

    if (!layout_found && layout != NULL && g_strcmp0 (layout, "")) {
        string = g_strdup_printf ("        Option \"XkbLayout\" \"%s\"", layout);
        g_debug ("Inserting new entry: '%s'", string);
        entry = xorg_confd_line_entry_new (string, layout, XORG_CONFD_LINE_TYPE_XKB_LAYOUT);
        parser->line_list = g_list_insert_before (parser->line_list, end, entry);
        g_free (string);
    }
    if (!model_found && model != NULL && g_strcmp0 (model, "")) {
        string = g_strdup_printf ("        Option \"XkbModel\" \"%s\"", model);
        g_debug ("Inserting new entry: '%s'", string);
        entry = xorg_confd_line_entry_new (string, model, XORG_CONFD_LINE_TYPE_XKB_MODEL);
        parser->line_list = g_list_insert_before (parser->line_list, end, entry);
        g_free (string);
    }
    if (!variant_found && variant != NULL && g_strcmp0 (variant, "")) {
        string = g_strdup_printf ("        Option \"XkbVariant\" \"%s\"", variant);
        g_debug ("Inserting new entry: '%s'", string);
        entry = xorg_confd_line_entry_new (string, variant, XORG_CONFD_LINE_TYPE_XKB_VARIANT);
        parser->line_list = g_list_insert_before (parser->line_list, end, entry);
        g_free (string);
    }
    if (!options_found && options != NULL && g_strcmp0 (options, "")) {
        string = g_strdup_printf ("        Option \"XkbOptions\" \"%s\"", options);
        g_debug ("Inserting new entry: '%s'", string);
        entry = xorg_confd_line_entry_new (string, options, XORG_CONFD_LINE_TYPE_XKB_OPTIONS);
        parser->line_list = g_list_insert_before (parser->line_list, end, entry);
        g_free (string);
    }
}

static gboolean
xorg_confd_parser_save (const struct xorg_confd_parser *parser,
                        GError **error)
{
    gboolean ret = FALSE;
    GList *curr = NULL;
    GFileOutputStream *os;

    g_assert (parser != NULL && parser->file != NULL && parser->filename != NULL);
    if ((os = g_file_replace (parser->file, NULL, FALSE, G_FILE_CREATE_NONE, NULL, error)) == NULL) {
        g_prefix_error (error, "Unable to save '%s': ", parser->filename);
        goto out;
    }

    for (curr = parser->line_list; curr != NULL; curr = curr->next) {
        struct xorg_confd_line_entry *entry = (struct xorg_confd_line_entry *) curr->data;
        gsize written;

        if (!g_output_stream_write_all (G_OUTPUT_STREAM (os), entry->string, strlen (entry->string), &written, NULL, error)) {
            g_prefix_error (error, "Unable to save '%s': ", parser->filename);
            goto out;
        }
        if (!g_output_stream_write_all (G_OUTPUT_STREAM (os), "\n", 1, &written, NULL, error)) {
            g_prefix_error (error, "Unable to save '%s': ", parser->filename);
            goto out;
        }
    }

    if (!g_output_stream_close (G_OUTPUT_STREAM (os), NULL, error)) {
        g_prefix_error (error, "Unable to save '%s': ", parser->filename);
        g_output_stream_close (G_OUTPUT_STREAM (os), NULL, NULL);
        goto out;
    }
    ret = TRUE;

  out:
    if (os)
        g_object_unref (os);
    return ret;
}

/* End of trivial /etc/X11/xorg.conf.d/30-keyboard.conf parser */

static gboolean
locale_name_is_valid (gchar *name)
{
    return g_regex_match_simple ("^[a-zA-Z0-9_.@-]*$", name, G_REGEX_MULTILINE, 0);
}

struct invoked_locale {
    GDBusMethodInvocation *invocation;
    gchar **locale; /* newly allocated */
};

static void
invoked_locale_free (struct invoked_locale *data)
{
    if (data == NULL)
        return;
    g_strfreev (data->locale);
    g_free (data);
}

static void
on_handle_set_locale_authorized_cb (GObject *source_object,
                                    GAsyncResult *res,
                                    gpointer user_data)
{
    GError *err = NULL;
    struct invoked_locale *data;
    gchar **loc, **var, **val, **locale_values = NULL;
    ShellParser *locale_file_parsed = NULL;

    data = (struct invoked_locale *) user_data;
    if (!check_polkit_finish (res, &err)) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        goto out;
    }

    G_LOCK (locale);
    locale_values = g_new0 (gchar *, g_strv_length (locale_variables) + 1);
    /* Don't allow unknown locale variables or invalid values */
    if (data->locale != NULL) {
        for (loc = data->locale; *loc != NULL; loc++) {
            gboolean found = FALSE;
            for (val = locale_values, var = locale_variables; *var != NULL; val++, var++) {
                size_t varlen;
                gchar *unquoted = NULL;

                varlen = strlen (*var);
                if (g_str_has_prefix (*loc, *var) && (*loc)[varlen] == '=' &&
                    (unquoted = g_shell_unquote (*loc + varlen + 1, NULL)) != NULL &&
                    locale_name_is_valid (unquoted)) {
                    found = TRUE;
                    if (*val != NULL)
                        g_free (*val);
                    *val = unquoted;
                } else
                    g_free (unquoted);
            }
            if (!found) {
                g_dbus_method_invocation_return_dbus_error (data->invocation, DBUS_ERROR_INVALID_ARGS,
                                                            "Invalid locale variable name or value");
                G_UNLOCK (locale);
                goto out;
            }
        }
    }

    if ((locale_file_parsed = shell_parser_new (locale_file, &err)) == NULL) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        G_UNLOCK (locale);
        goto out;
    }

    if (shell_parser_is_empty (locale_file_parsed)) {
        /* Simply write the new env file */
        shell_parser_free (locale_file_parsed);
        if ((locale_file_parsed = shell_parser_new_from_string (locale_file, "# Configuration file for eselect\n# This file has been automatically generated\n", &err)) == NULL) {
            g_dbus_method_invocation_return_gerror (data->invocation, err);
            G_UNLOCK (locale);
            goto out;
        }
    }

    for (val = locale_values, var = locale_variables; *var != NULL; val++, var++) {
        if (*val == NULL)
            shell_parser_clear_variable (locale_file_parsed, *var);
        else
            shell_parser_set_variable (locale_file_parsed, *var, *val, TRUE);
    }

    if (!shell_parser_save (locale_file_parsed, &err)) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        G_UNLOCK (locale);
        goto out;
    }

    g_strfreev (locale);
    locale = g_new0 (gchar *, g_strv_length (locale_variables) + 1);
    loc = locale;
    for (val = locale_values, var = locale_variables; *var != NULL; val++, var++) {
        if (*val != NULL) {
            *loc = g_strdup_printf ("%s=%s", *var, *val);
            loc++;
        }
    }

    openrc_settingsd_localed_locale1_complete_set_locale (locale1, data->invocation);
    openrc_settingsd_localed_locale1_set_locale (locale1, (const gchar * const *) locale);
    G_UNLOCK (locale);

  out:
    shell_parser_free (locale_file_parsed);
    /* g_strfreev (locale_values) will leak, since it stops at first NULL value */
    for (val = locale_values, var = locale_variables; *var != NULL; val++, var++)
        g_free (*val);
    g_free (locale_values);
    invoked_locale_free (data);
    if (err != NULL)
        g_error_free (err);
}

static gboolean
on_handle_set_locale (OpenrcSettingsdLocaledLocale1 *locale1,
                      GDBusMethodInvocation *invocation,
                      const gchar * const *_locale,
                      const gboolean user_interaction,
                      gpointer user_data)
{
    if (read_only)
        g_dbus_method_invocation_return_dbus_error (invocation,
                                                    DBUS_ERROR_NOT_SUPPORTED,
                                                    SERVICE_NAME " is in read-only mode");
    else {
        struct invoked_locale *data;
        data = g_new0 (struct invoked_locale, 1);
        data->invocation = invocation;
        data->locale = g_strdupv ((gchar**)_locale);
        check_polkit_async (g_dbus_method_invocation_get_sender (invocation), "org.freedesktop.locale1.set-locale", user_interaction, on_handle_set_locale_authorized_cb, data);
    }

    return TRUE;
}

struct invoked_vconsole_keyboard {
    GDBusMethodInvocation *invocation;
    gchar *vconsole_keymap; /* newly allocated */
    gchar *vconsole_keymap_toggle; /* newly allocated */
    gboolean convert;
};

static void
invoked_vconsole_keyboard_free (struct invoked_vconsole_keyboard *data)
{
    if (data == NULL)
        return;
    g_free (data->vconsole_keymap);
    g_free (data->vconsole_keymap_toggle);
    g_free (data);
}

static void
on_handle_set_vconsole_keyboard_authorized_cb (GObject *source_object,
                                               GAsyncResult *res,
                                               gpointer user_data)
{
    GError *err = NULL;
    struct invoked_vconsole_keyboard *data;
    GList *kbd_model_map = NULL;
    struct kbd_model_map_entry *best_entry = NULL;
    struct xorg_confd_parser *x11_parser = NULL;

    data = (struct invoked_vconsole_keyboard *) user_data;
    if (!check_polkit_finish (res, &err)) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        goto out;
    }

    G_LOCK (keymaps);
    if (data->convert) {
        GList *cur;

        G_LOCK (xorg_conf);
        kbd_model_map = kbd_model_map_load (&err);
        if (err != NULL) {
            g_dbus_method_invocation_return_gerror (data->invocation, err);
            goto unlock;
        }

        for (cur = kbd_model_map; cur->next != NULL; cur = cur->next) {
            struct kbd_model_map_entry *cur_entry = NULL;
            cur_entry = (struct kbd_model_map_entry *) cur->data;
            if (kbd_model_map_entry_matches_vconsole (cur_entry, data->vconsole_keymap)) {
                best_entry = cur_entry;
                break;
            }
        }
    }

    /* We do not set vconsole_keymap_toggle because there is no good equivalent for it in OpenRC */
    if (!shell_parser_set_and_save (keymaps_file, &err, "keymap", NULL, data->vconsole_keymap, NULL)) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        goto unlock;
    }

    g_free (vconsole_keymap);
    vconsole_keymap = g_strdup (data->vconsole_keymap);
    openrc_settingsd_localed_locale1_set_vconsole_keymap (locale1, vconsole_keymap);

    if (data->convert) {
        if (best_entry == NULL) {
            gchar *filename;
            filename = g_file_get_path (kbd_model_map_file);
            g_printerr ("Failed to find conversion entry for console keymap '%s' in '%s'\n", data->vconsole_keymap, filename);
            g_free (filename);
            G_UNLOCK (xorg_conf);
        } else {
            unsigned int failure_score = 0;

            kbd_model_map_entry_matches_x11 (best_entry, x11_layout, x11_model, x11_variant, x11_options, &failure_score);
            if (failure_score > 0) {
                /* The xkb data has changed, so we want to update it */
                if (!g_file_query_exists (x11_gentoo_file, NULL) && g_file_query_exists (x11_systemd_file, NULL))
                    x11_parser = xorg_confd_parser_new (x11_systemd_file, &err);
                else
                    x11_parser = xorg_confd_parser_new (x11_gentoo_file, &err);

                if (x11_parser == NULL) {
                    g_dbus_method_invocation_return_gerror (data->invocation, err);
                    goto unlock;
                }
                xorg_confd_parser_set_xkb (x11_parser, best_entry->x11_layout, best_entry->x11_model, best_entry->x11_variant, best_entry->x11_options);
                if (!xorg_confd_parser_save (x11_parser, &err)) {
                    g_dbus_method_invocation_return_gerror (data->invocation, err);
                    goto unlock;
                }
                g_free (x11_layout);
                g_free (x11_model);
                g_free (x11_variant);
                g_free (x11_options);
                x11_layout = g_strdup (best_entry->x11_layout);
                x11_model = g_strdup (best_entry->x11_model);
                x11_variant = g_strdup (best_entry->x11_variant);
                x11_options = g_strdup (best_entry->x11_options);
                openrc_settingsd_localed_locale1_set_x11_layout (locale1, x11_layout);
                openrc_settingsd_localed_locale1_set_x11_model (locale1, x11_model);
                openrc_settingsd_localed_locale1_set_x11_variant (locale1, x11_variant);
                openrc_settingsd_localed_locale1_set_x11_options (locale1, x11_options);
            }
        }
    }
    /* We do not modify vconsole_keymap_toggle because there is no good equivalent for it in OpenRC */
    openrc_settingsd_localed_locale1_complete_set_vconsole_keyboard (locale1, data->invocation);

  unlock:
    if (data->convert)
        G_UNLOCK (xorg_conf);
    G_UNLOCK (keymaps);

  out:
    if (kbd_model_map != NULL)
        g_list_free_full (kbd_model_map, (GDestroyNotify)kbd_model_map_entry_free);
    xorg_confd_parser_free (x11_parser);
    invoked_vconsole_keyboard_free (data);
    if (err != NULL)
        g_error_free (err);
}

static gboolean
on_handle_set_vconsole_keyboard (OpenrcSettingsdLocaledLocale1 *locale1,
                                 GDBusMethodInvocation *invocation,
                                 const gchar *keymap,
                                 const gchar *keymap_toggle,
                                 const gboolean convert,
                                 const gboolean user_interaction,
                                 gpointer user_data)
{
    if (read_only)
        g_dbus_method_invocation_return_dbus_error (invocation,
                                                    DBUS_ERROR_NOT_SUPPORTED,
                                                    SERVICE_NAME " is in read-only mode");
    else {
        struct invoked_vconsole_keyboard *data;
        data = g_new0 (struct invoked_vconsole_keyboard, 1);
        data->invocation = invocation;
        data->vconsole_keymap = g_strdup (keymap);
        data->vconsole_keymap_toggle = g_strdup (keymap_toggle);
        data->convert = convert;
        check_polkit_async (g_dbus_method_invocation_get_sender (invocation), "org.freedesktop.locale1.set-keyboard", user_interaction, on_handle_set_vconsole_keyboard_authorized_cb, data);
    }

    return TRUE;
}

struct invoked_x11_keyboard {
    GDBusMethodInvocation *invocation;
    gchar *x11_layout; /* newly allocated */
    gchar *x11_model; /* newly allocated */
    gchar *x11_variant; /* newly allocated */
    gchar *x11_options; /* newly allocated */
    gboolean convert;
};

static void
invoked_x11_keyboard_free (struct invoked_x11_keyboard *data)
{
    if (data == NULL)
        return;
    g_free (data->x11_layout);
    g_free (data->x11_model);
    g_free (data->x11_variant);
    g_free (data->x11_options);
    g_free (data);
}

static void
on_handle_set_x11_keyboard_authorized_cb (GObject *source_object,
                                          GAsyncResult *res,
                                          gpointer user_data)
{
    GError *err = NULL;
    struct invoked_x11_keyboard *data;
    GList *kbd_model_map = NULL;
    struct kbd_model_map_entry *best_entry = NULL;
    unsigned int best_failure_score = UINT_MAX;
    struct xorg_confd_parser *x11_parser = NULL;

    data = (struct invoked_x11_keyboard *) user_data;
    if (!check_polkit_finish (res, &err)) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        goto out;
    }

    G_LOCK (xorg_conf);
    if (data->convert) {
        GList *cur;

        G_LOCK (keymaps);
        kbd_model_map = kbd_model_map_load (&err);
        if (err != NULL) {
            g_dbus_method_invocation_return_gerror (data->invocation, err);
            goto unlock;
        }

        for (cur = kbd_model_map; cur->next != NULL; cur = cur->next) {
            struct kbd_model_map_entry *cur_entry = NULL;
            unsigned int cur_failure_score = 0;

            cur_entry = (struct kbd_model_map_entry *) cur->data;
            if (kbd_model_map_entry_matches_x11 (cur_entry, data->x11_layout, data->x11_model, data->x11_variant, data->x11_options, &cur_failure_score))
                if (cur_failure_score < best_failure_score) {
                    best_entry = cur_entry;
                    best_failure_score = cur_failure_score;
                }
        }
    }

    if (!g_file_query_exists (x11_gentoo_file, NULL) && g_file_query_exists (x11_systemd_file, NULL))
        x11_parser = xorg_confd_parser_new (x11_systemd_file, &err);
    else
        x11_parser = xorg_confd_parser_new (x11_gentoo_file, &err);

    if (x11_parser == NULL) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        goto unlock;
    }
    xorg_confd_parser_set_xkb (x11_parser, data->x11_layout, data->x11_model, data->x11_variant, data->x11_options);
    if (!xorg_confd_parser_save (x11_parser, &err)) {
        g_dbus_method_invocation_return_gerror (data->invocation, err);
        goto unlock;
    }
    g_free (x11_layout);
    g_free (x11_model);
    g_free (x11_variant);
    g_free (x11_options);
    x11_layout = g_strdup (data->x11_layout);
    x11_model = g_strdup (data->x11_model);
    x11_variant = g_strdup (data->x11_variant);
    x11_options = g_strdup (data->x11_options);
    openrc_settingsd_localed_locale1_set_x11_layout (locale1, x11_layout);
    openrc_settingsd_localed_locale1_set_x11_model (locale1, x11_model);
    openrc_settingsd_localed_locale1_set_x11_variant (locale1, x11_variant);
    openrc_settingsd_localed_locale1_set_x11_options (locale1, x11_options);

    if (data->convert) {
        if (best_entry == NULL) {
            gchar *filename;
            filename = g_file_get_path (kbd_model_map_file);
            g_printerr ("Failed to find conversion entry for x11 layout '%s' in '%s'\n", data->x11_layout, filename);
            g_free (filename);
        } else {
            if (!shell_parser_set_and_save (keymaps_file, &err, "keymap", NULL, best_entry->vconsole_keymap, NULL)) {
                g_dbus_method_invocation_return_gerror (data->invocation, err);
                goto unlock;
            }
            g_free (vconsole_keymap);
            vconsole_keymap = g_strdup (best_entry->vconsole_keymap);
            openrc_settingsd_localed_locale1_set_vconsole_keymap (locale1, vconsole_keymap);
        }
    }

    openrc_settingsd_localed_locale1_complete_set_x11_keyboard (locale1, data->invocation);

  unlock:
    if (data->convert)
        G_UNLOCK (keymaps);
    G_UNLOCK (xorg_conf);

  out:
    if (kbd_model_map != NULL)
        g_list_free_full (kbd_model_map, (GDestroyNotify)kbd_model_map_entry_free);
    xorg_confd_parser_free (x11_parser);
    invoked_x11_keyboard_free (data);
    if (err != NULL)
        g_error_free (err);
}

static gboolean
on_handle_set_x11_keyboard (OpenrcSettingsdLocaledLocale1 *locale1,
                            GDBusMethodInvocation *invocation,
                            const gchar *layout,
                            const gchar *model,
                            const gchar *variant,
                            const gchar *options,
                            const gboolean convert,
                            const gboolean user_interaction,
                            gpointer user_data)
{
    if (read_only)
        g_dbus_method_invocation_return_dbus_error (invocation,
                                                    DBUS_ERROR_NOT_SUPPORTED,
                                                    SERVICE_NAME " is in read-only mode");
    else {
        struct invoked_x11_keyboard *data;
        data = g_new0 (struct invoked_x11_keyboard, 1);
        data->invocation = invocation;
        data->x11_layout = g_strdup (layout);
        data->x11_model = g_strdup (model);
        data->x11_variant = g_strdup (variant);
        data->x11_options = g_strdup (options);
        data->convert = convert;
        check_polkit_async (g_dbus_method_invocation_get_sender (invocation), "org.freedesktop.locale1.set-keyboard", user_interaction, on_handle_set_x11_keyboard_authorized_cb, data);
    }

    return TRUE;
}

static void
on_bus_acquired (GDBusConnection *connection,
                 const gchar     *bus_name,
                 gpointer         user_data)
{
    gchar *name;
    GError *err = NULL;

    g_debug ("Acquired a message bus connection");

    locale1 = openrc_settingsd_localed_locale1_skeleton_new ();

    openrc_settingsd_localed_locale1_set_locale (locale1, (const gchar * const *) locale);
    openrc_settingsd_localed_locale1_set_vconsole_keymap (locale1, vconsole_keymap);
    openrc_settingsd_localed_locale1_set_vconsole_keymap_toggle (locale1, vconsole_keymap_toggle);
    openrc_settingsd_localed_locale1_set_x11_layout (locale1, x11_layout);
    openrc_settingsd_localed_locale1_set_x11_model (locale1, x11_model);
    openrc_settingsd_localed_locale1_set_x11_variant (locale1, x11_variant);
    openrc_settingsd_localed_locale1_set_x11_options (locale1, x11_options);

    g_signal_connect (locale1, "handle-set-locale", G_CALLBACK (on_handle_set_locale), NULL);
    g_signal_connect (locale1, "handle-set-vconsole-keyboard", G_CALLBACK (on_handle_set_vconsole_keyboard), NULL);
    g_signal_connect (locale1, "handle-set-x11-keyboard", G_CALLBACK (on_handle_set_x11_keyboard), NULL);

    if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (locale1),
                                           connection,
                                           "/org/freedesktop/locale1",
                                           &err)) {
        if (err != NULL) {
            g_critical ("Failed to export interface on /org/freedesktop/locale1: %s", err->message);
            openrc_settingsd_exit (1);
        }
    }
}

static void
on_name_acquired (GDBusConnection *connection,
                  const gchar     *bus_name,
                  gpointer         user_data)
{
    g_debug ("Acquired the name %s", bus_name);
    openrc_settingsd_component_started ();
}

static void
on_name_lost (GDBusConnection *connection,
              const gchar     *bus_name,
              gpointer         user_data)
{
    if (connection == NULL)
        g_critical ("Failed to acquire a dbus connection");
    else
        g_critical ("Failed to acquire dbus name %s", bus_name);
    openrc_settingsd_exit (1);
}

void
localed_init (gboolean _read_only)
{
    GError *err = NULL;
    gchar **locale_values = NULL;
    struct xorg_confd_parser *x11_parser = NULL;

    read_only = _read_only;
    kbd_model_map_file = g_file_new_for_path (PKGDATADIR "/kbd-model-map");
    locale_file = g_file_new_for_path (SYSCONFDIR "/env.d/02locale");
    keymaps_file = g_file_new_for_path (SYSCONFDIR "/conf.d/keymaps");

    /* See http://www.gentoo.org/doc/en/xorg-config.xml */
    x11_gentoo_file = g_file_new_for_path (SYSCONFDIR "/X11/xorg.conf.d/30-keyboard.conf");
    x11_systemd_file = g_file_new_for_path (SYSCONFDIR "/X11/xorg.conf.d/00-keyboard.conf");

    locale = g_new0 (gchar *, g_strv_length (locale_variables) + 1);
    locale_values = shell_parser_source_var_list (locale_file, (const gchar * const *)locale_variables, &err);
    if (locale_values != NULL) {
        gchar **variable, **value, **loc;
        loc = locale;
        for (variable = locale_variables, value = locale_values; *variable != NULL; variable++, value++) {
            if (*value != NULL) {
                *loc = g_strdup_printf ("%s=%s", *variable, *value);
                g_free (*value);
                loc++;
            }
        }
            
        g_free (locale_values);
    }
    if (err != NULL) {
        g_debug ("%s", err->message);
        g_clear_error (&err);
    }

    vconsole_keymap = shell_source_var (keymaps_file, "${keymap}", &err);
    if (vconsole_keymap == NULL)
        vconsole_keymap = g_strdup ("");
    if (err != NULL) {
        g_debug ("%s", err->message);
        g_clear_error (&err);
    }

    /* We don't have a good equivalent for this in openrc at the moment */
    vconsole_keymap_toggle = g_strdup ("");

    kbd_model_map_regex_init ();
    xorg_confd_regex_init ();

    if (!g_file_query_exists (x11_gentoo_file, NULL) && g_file_query_exists (x11_systemd_file, NULL))
        x11_parser = xorg_confd_parser_new (x11_systemd_file, &err);
    else
        x11_parser = xorg_confd_parser_new (x11_gentoo_file, &err);

    if (x11_parser != NULL) {
        xorg_confd_parser_get_xkb (x11_parser, &x11_layout, &x11_model, &x11_variant, &x11_options);
        xorg_confd_parser_free (x11_parser);
    } else {
        g_debug ("%s", err->message);
        g_clear_error (&err);
    }

    bus_id = g_bus_own_name (G_BUS_TYPE_SYSTEM,
                             "org.freedesktop.locale1",
                             G_BUS_NAME_OWNER_FLAGS_NONE,
                             on_bus_acquired,
                             on_name_acquired,
                             on_name_lost,
                             NULL,
                             NULL);
}

void
localed_destroy (void)
{
    g_bus_unown_name (bus_id);
    bus_id = 0;
    read_only = FALSE;
    g_strfreev (locale);
    kbd_model_map_regex_destroy ();
    xorg_confd_regex_destroy ();
    g_free (vconsole_keymap);
    g_free (vconsole_keymap_toggle);
    g_free (x11_layout);
    g_free (x11_model);
    g_free (x11_variant);
    g_free (x11_options);

    g_object_unref (locale_file);
    g_object_unref (keymaps_file);
    g_object_unref (x11_gentoo_file);
    g_object_unref (x11_systemd_file);
    g_object_unref (kbd_model_map_file);
}