summaryrefslogtreecommitdiffstats
path: root/src/sbus/sssd_dbus_interface.c
blob: f8046c7c137d7e5762d92c7c1ebec876b84390ef (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
/*
    Authors:
        Pavel Březina <pbrezina@redhat.com>

    Copyright (C) 2014 Red Hat

    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 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <talloc.h>
#include <dbus/dbus.h>
#include <dhash.h>

#include "util/util.h"
#include "sbus/sssd_dbus.h"
#include "sbus/sssd_dbus_meta.h"
#include "sbus/sssd_dbus_private.h"

static struct sbus_interface *
sbus_iface_list_lookup(struct sbus_interface_list *list,
                       const char *iface)
{
    struct sbus_interface_list *item;

    DLIST_FOR_EACH(item, list) {
        if (strcmp(item->interface->vtable->meta->name, iface) == 0) {
            return item->interface;
        }
    }

    return NULL;
}

static errno_t
sbus_iface_list_copy(TALLOC_CTX *mem_ctx,
                     struct sbus_interface_list *list,
                     struct sbus_interface_list **_copy)
{
    TALLOC_CTX *list_ctx;
    struct sbus_interface_list *new_list = NULL;
    struct sbus_interface_list *new_item;
    struct sbus_interface_list *item;
    errno_t ret;

    if (list == NULL) {
        *_copy = NULL;
        return EOK;
    }

    list_ctx = talloc_new(mem_ctx);
    if (list_ctx == NULL) {
        return ENOMEM;
    }

    DLIST_FOR_EACH(item, list) {
        if (sbus_iface_list_lookup(new_list,
               item->interface->vtable->meta->name) != NULL) {
            /* already in list */
            continue;
        }

        new_item = talloc_zero(list_ctx, struct sbus_interface_list);
        if (new_item == NULL) {
            ret = ENOMEM;
            goto done;
        }

        new_item->interface = item->interface;
        DLIST_ADD(new_list, new_item);
    }

    *_copy = new_list;
    ret = EOK;

done:
    if (ret != EOK) {
        talloc_free(list_ctx);
    }

    return ret;
}

/**
 * Object paths that represent all objects under the path:
 * /org/object/path/~* (without tilda)
 */
static bool sbus_opath_is_subtree(const char *path)
{
    size_t len;

    len = strlen(path);

    if (len < 2) {
        return false;
    }

    return path[len - 2] == '/' && path[len - 1] == '*';
}

/**
 * If the path represents a subtree object path, this function will
 * remove /~* from the end.
 */
static char *sbus_opath_get_base_path(TALLOC_CTX *mem_ctx,
                                      const char *object_path)
{
    char *tree_path;
    size_t len;

    tree_path = talloc_strdup(mem_ctx, object_path);
    if (tree_path == NULL) {
        return NULL;
    }

    if (!sbus_opath_is_subtree(tree_path)) {
        return tree_path;
    }

    /* replace / only if it is not a root path (only slash) */
    len = strlen(tree_path);
    tree_path[len - 1] = '\0';
    tree_path[len - 2] = (len - 2 != 0) ? '\0' : '/';

    return tree_path;
}

static char *sbus_opath_parent_subtree(TALLOC_CTX *mem_ctx,
                                       const char *path)
{
    char *subtree;
    char *slash;

    /* first remove /~* from the end, stop when we have reached the root i.e.
     * subtree == "/" */
    subtree = sbus_opath_get_base_path(mem_ctx, path);
    if (subtree == NULL || subtree[1] == '\0') {
        return NULL;
    }

    /* Find the first separator and replace the part with asterisk. */
    slash = strrchr(subtree, '/');
    if (slash == NULL) {
        /* we cannot continue up */
        talloc_free(subtree);
        return NULL;
    }

    if (*(slash + 1) == '\0') {
        /* this object path is invalid since it cannot end with slash */
        DEBUG(SSSDBG_CRIT_FAILURE, "Invalid object path '%s'?\n", path);
        talloc_free(subtree);
        return NULL;
    }

    /* because object path cannot end with / there is enough space for
     * asterisk and terminating zero */
    *(slash + 1) = '*';
    *(slash + 2) = '\0';

    return subtree;
}

/**
 * The following path related functions are based on similar code in
 * storaged, just tailored to use talloc instead of glib
 */
char *
sbus_opath_escape_part(TALLOC_CTX *mem_ctx,
                       const char *object_path_part)
{
    size_t n;
    char *safe_path = NULL;
    TALLOC_CTX *tmp_ctx = NULL;

    /* The path must be valid */
    if (object_path_part == NULL) {
        return NULL;
    }

    tmp_ctx = talloc_new(NULL);
    if (tmp_ctx == NULL) {
        return NULL;
    }

    safe_path = talloc_strdup(tmp_ctx, "");
    if (safe_path == NULL) {
        goto done;
    }

    /* Special case for an empty string */
    if (strcmp(object_path_part, "") == 0) {
        /* the for loop would just fall through */
        safe_path = talloc_asprintf_append_buffer(safe_path, "_");
        if (safe_path == NULL) {
            goto done;
        }
    }

    for (n = 0; object_path_part[n]; n++) {
        int c = object_path_part[n];
        /* D-Bus spec says:
         * *
         * * Each element must only contain the ASCII characters
         * "[A-Z][a-z][0-9]_"
         * */
        if ((c >= 'A' && c <= 'Z')
                || (c >= 'a' && c <= 'z')
                || (c >= '0' && c <= '9')) {
            safe_path = talloc_asprintf_append_buffer(safe_path, "%c", c);
            if (safe_path == NULL) {
                goto done;
            }
        } else {
            safe_path = talloc_asprintf_append_buffer(safe_path, "_%02x", c);
            if (safe_path == NULL) {
                goto done;
            }
        }
    }

    safe_path = talloc_steal(mem_ctx, safe_path);

done:
    talloc_free(tmp_ctx);
    return safe_path;
}

static inline int unhexchar(char c)
{
    if (c >= '0' && c <= '9') {
        return c - '0';
    }

    if (c >= 'a' && c <= 'f') {
        return c - 'a' + 10;
    }

    if (c >= 'A' && c <= 'F') {
        return c - 'A' + 10;
    }

    return -1;
}

char *
sbus_opath_unescape_part(TALLOC_CTX *mem_ctx,
                         const char *object_path_part)
{
    char *safe_path;
    const char *p;
    int a, b, c;
    TALLOC_CTX *tmp_ctx = NULL;

    tmp_ctx = talloc_new(NULL);
    if (tmp_ctx == NULL) {
        return NULL;
    }

    safe_path = talloc_strdup(tmp_ctx, "");
    if (safe_path == NULL) {
        goto done;
    }

    /* Special case for the empty string */
    if (strcmp(object_path_part, "_") == 0) {
        safe_path = talloc_steal(mem_ctx, safe_path);
        goto done;
    }

    for (p = object_path_part; *p; p++) {
        if (*p == '_') {
            /* There must be at least two more chars after underscore */
            if (p[1] == '\0' || p[2] == '\0') {
                safe_path = NULL;
                goto done;
            }

            if ((a = unhexchar(p[1])) < 0
                    || (b = unhexchar(p[2])) < 0) {
                /* Invalid escape code, let's take it literal then */
                c = '_';
            } else {
                c = ((a << 4) | b);
                p += 2;
            }
        } else  {
            c = *p;
        }

        safe_path = talloc_asprintf_append_buffer(safe_path, "%c", c);
        if (safe_path == NULL) {
            goto done;
        }
    }

    safe_path = talloc_steal(mem_ctx, safe_path);

done:
    talloc_free(tmp_ctx);
    return safe_path;
}

char *
_sbus_opath_compose(TALLOC_CTX *mem_ctx,
                    const char *base,
                    const char *part, ...)
{
    char *safe_part;
    char *path = NULL;
    va_list va;

    if (base == NULL) {
        DEBUG(SSSDBG_OP_FAILURE, "Wrong object path base!\n");
        return NULL;
    }

    path = talloc_strdup(mem_ctx, base);
    if (path == NULL) return NULL;

    va_start(va, part);
    while (part != NULL) {
        safe_part = sbus_opath_escape_part(mem_ctx, part);
        if (safe_part == NULL) {
            DEBUG(SSSDBG_OP_FAILURE, "Could not add [%s] to objpath\n", part);
            goto fail;
        }

        path = talloc_asprintf_append(path, "/%s", safe_part);
        talloc_free(safe_part);
        if (path == NULL) {
            goto fail;
        }

        part = va_arg(va, const char *);
    }
    va_end(va);

    return path;

fail:
    va_end(va);
    talloc_free(path);
    return NULL;
}

errno_t
sbus_opath_decompose(TALLOC_CTX *mem_ctx,
                     const char *object_path,
                     const char *prefix,
                     char ***_components,
                     size_t *_len)
{
    TALLOC_CTX *tmp_ctx;
    const char *path;
    char **decomposed;
    char **unescaped;
    errno_t ret;
    int len;
    int i;

    tmp_ctx = talloc_new(NULL);
    if (tmp_ctx == NULL) {
        return ENOMEM;
    }

    /* Strip prefix from the path. */
    if (prefix != NULL) {
        path = sbus_opath_strip_prefix(object_path, prefix);
        if (path == NULL) {
            ret = ERR_SBUS_INVALID_PATH;
            goto done;
        }
    } else {
        path = object_path;
    }

    /* Split the string using / as delimiter. */
    split_on_separator(tmp_ctx, path, '/', true, true, &decomposed, &len);

    /* Unescape parts. */
    unescaped = talloc_zero_array(tmp_ctx, char *, len + 1);
    if (unescaped == NULL) {
        ret = ENOMEM;
        goto done;
    }

    for (i = 0; i < len; i++) {
        unescaped[i] = sbus_opath_unescape_part(unescaped, decomposed[i]);
        if (unescaped[i] == NULL) {
            ret = ENOMEM;
            goto done;
        }
    }

    if (_components != NULL) {
        *_components = talloc_steal(mem_ctx, unescaped);
    }

    if (_len != NULL) {
        *_len = len;
    }

    ret = EOK;

done:
    talloc_free(tmp_ctx);
    return ret;
}

errno_t
sbus_opath_decompose_exact(TALLOC_CTX *mem_ctx,
                           const char *object_path,
                           const char *prefix,
                           size_t expected,
                           char ***_components)
{
    char **components;
    size_t len;
    errno_t ret;

    ret = sbus_opath_decompose(mem_ctx, object_path, prefix,
                               &components, &len);
    if (ret != EOK) {
        return ret;
    }

    if (len != expected) {
        talloc_free(components);
        return ERR_SBUS_INVALID_PATH;
    }

    if (_components != NULL) {
        *_components = components;
    }

    return EOK;
}

const char *
sbus_opath_strip_prefix(const char *object_path,
                        const char *prefix)
{
    if (strncmp(object_path, prefix, strlen(prefix)) == 0) {
        return object_path + strlen(prefix);
    }

    return NULL;
}

char *
sbus_opath_get_object_name(TALLOC_CTX *mem_ctx,
                           const char *object_path,
                           const char *base_path)
{
    const char *name;

    name = sbus_opath_strip_prefix(object_path, base_path);
    if (name == NULL || name[0] == '\0') {
        return NULL;
    }

    /* if base_path did not end with / */
    if (name[0] == '/') {
        name = name + 1;
    }

    return sbus_opath_unescape_part(mem_ctx, name);
}

static void
sbus_opath_hash_delete_cb(hash_entry_t *item,
                          hash_destroy_enum deltype,
                          void *pvt)
{
    struct sbus_connection *conn;
    char *path;

    conn = talloc_get_type(pvt, struct sbus_connection);
    path = sbus_opath_get_base_path(NULL, item->key.str);

    dbus_connection_unregister_object_path(conn->dbus.conn, path);
}

errno_t
sbus_opath_hash_init(TALLOC_CTX *mem_ctx,
                     struct sbus_connection *conn,
                     hash_table_t **_table)
{
    return sss_hash_create_ex(mem_ctx, 10, _table, 0, 0, 0, 0,
                              sbus_opath_hash_delete_cb, conn);
}

static errno_t
sbus_opath_hash_add_iface(hash_table_t *table,
                          const char *object_path,
                          struct sbus_interface *iface,
                          bool *_path_known)
{
    TALLOC_CTX *tmp_ctx = NULL;
    struct sbus_interface_list *list = NULL;
    struct sbus_interface_list *item = NULL;
    const char *iface_name = iface->vtable->meta->name;
    hash_key_t key;
    hash_value_t value;
    bool path_known;
    errno_t ret;
    int hret;

    tmp_ctx = talloc_new(NULL);
    if (tmp_ctx == NULL) {
        return ENOMEM;
    }

    DEBUG(SSSDBG_TRACE_FUNC, "Registering interface %s with path %s\n",
          iface_name, object_path);

    /* create new list item */

    item = talloc_zero(tmp_ctx, struct sbus_interface_list);
    if (item == NULL) {
        return ENOMEM;
    }

    item->interface = iface;

    /* first lookup existing list in hash table */

    key.type = HASH_KEY_STRING;
    key.str = talloc_strdup(tmp_ctx, object_path);
    if (key.str == NULL) {
        ret = ENOMEM;
        goto done;
    }

    hret = hash_lookup(table, &key, &value);
    if (hret == HASH_SUCCESS) {
        /* This object path has already some interface registered. We will
         * check for existence of the interface currently being added and
         * add it if missing. */

        path_known = true;

        list = talloc_get_type(value.ptr, struct sbus_interface_list);
        if (sbus_iface_list_lookup(list, iface_name) != NULL) {
            DEBUG(SSSDBG_MINOR_FAILURE, "Trying to register the same interface"
                  " twice: iface=%s, opath=%s\n", iface_name, object_path);
            ret = EEXIST;
            goto done;
        }

        DLIST_ADD_END(list, item, struct sbus_interface_list *);
        ret = EOK;
        goto done;
    } else if (hret != HASH_ERROR_KEY_NOT_FOUND) {
        ret = EIO;
        goto done;
    }

    /* otherwise create new hash entry and new list */

    path_known = false;
    list = item;

    value.type = HASH_VALUE_PTR;
    value.ptr = list;

    hret = hash_enter(table, &key, &value);
    if (hret != HASH_SUCCESS) {
        ret = EIO;
        goto done;
    }

    talloc_steal(table, key.str);
    ret = EOK;

done:
    if (ret == EOK) {
        talloc_steal(item, iface);
        talloc_steal(table, item);
        *_path_known = path_known;
    }

    talloc_free(tmp_ctx);
    return ret;
}

static bool
sbus_opath_hash_has_path(hash_table_t *table,
                         const char *object_path)
{
    hash_key_t key;

    key.type = HASH_KEY_STRING;
    key.str = discard_const(object_path);

    return hash_has_key(table, &key);
}

/**
 * First @object_path is looked up in @table, if it is not found it steps up
 * in the path hierarchy and try to lookup the parent node. This continues
 * until the root is reached.
 */
struct sbus_interface *
sbus_opath_hash_lookup_iface(hash_table_t *table,
                             const char *object_path,
                             const char *iface_name)
{
    TALLOC_CTX *tmp_ctx = NULL;
    struct sbus_interface_list *list = NULL;
    struct sbus_interface *iface = NULL;
    char *lookup_path = NULL;
    hash_key_t key;
    hash_value_t value;
    int hret;

    tmp_ctx = talloc_new(NULL);
    if (tmp_ctx == NULL) {
        return NULL;
    }

    lookup_path = talloc_strdup(tmp_ctx, object_path);
    if (lookup_path == NULL) {
        goto done;
    }

    while (lookup_path != NULL) {
        key.type = HASH_KEY_STRING;
        key.str = lookup_path;

        hret = hash_lookup(table, &key, &value);
        if (hret == HASH_SUCCESS) {
            list = talloc_get_type(value.ptr, struct sbus_interface_list);
            iface = sbus_iface_list_lookup(list, iface_name);
            if (iface != NULL) {
                goto done;
            }
        } else if (hret != HASH_ERROR_KEY_NOT_FOUND) {
            DEBUG(SSSDBG_OP_FAILURE,
                  "Unable to search hash table: hret=%d\n", hret);
            iface = NULL;
            goto done;
        }

        /* we will not free lookup path since it is freed with tmp_ctx
         * and the object paths are supposed to be small */
        lookup_path = sbus_opath_parent_subtree(tmp_ctx, lookup_path);
    }

done:
    talloc_free(tmp_ctx);
    return iface;
}

/**
 * Acquire list of all interfaces that are supported on given object path.
 */
errno_t
sbus_opath_hash_lookup_supported(TALLOC_CTX *mem_ctx,
                                 hash_table_t *table,
                                 const char *object_path,
                                 struct sbus_interface_list **_list)
{
    TALLOC_CTX *tmp_ctx = NULL;
    TALLOC_CTX *list_ctx = NULL;
    struct sbus_interface_list *copy = NULL;
    struct sbus_interface_list *list = NULL;
    char *lookup_path = NULL;
    hash_key_t key;
    hash_value_t value;
    errno_t ret;
    int hret;

    tmp_ctx = talloc_new(NULL);
    if (tmp_ctx == NULL) {
        return ENOMEM;
    }

    list_ctx = talloc_new(tmp_ctx);
    if (list_ctx == NULL) {
        ret = ENOMEM;
        goto done;
    }

    lookup_path = talloc_strdup(tmp_ctx, object_path);
    if (lookup_path == NULL) {
        ret = ENOMEM;
        goto done;
    }

    while (lookup_path != NULL) {
        key.type = HASH_KEY_STRING;
        key.str = lookup_path;

        hret = hash_lookup(table, &key, &value);
        if (hret == HASH_SUCCESS) {
            ret = sbus_iface_list_copy(list_ctx, value.ptr, &copy);
            if (ret != EOK) {
                goto done;
            }

            DLIST_CONCATENATE(list, copy, struct sbus_interface_list *);
        } else if (hret != HASH_ERROR_KEY_NOT_FOUND) {
            DEBUG(SSSDBG_OP_FAILURE,
                  "Unable to search hash table: hret=%d\n", hret);
            ret = EIO;
            goto done;
        }

        /* we will not free lookup path since it is freed with tmp_ctx
         * and the object paths are supposed to be small */
        lookup_path = sbus_opath_parent_subtree(tmp_ctx, lookup_path);
    }

    talloc_steal(mem_ctx, list_ctx);
    *_list = list;
    ret = EOK;

done:
    talloc_free(tmp_ctx);
    return ret;
}

errno_t
sbus_nodes_hash_init(TALLOC_CTX *mem_ctx,
                     struct sbus_connection *conn,
                     hash_table_t **_table)
{
    return sss_hash_create_ex(mem_ctx, 10, _table, 0, 0, 0, 0,
                              NULL, conn);
}

struct sbus_nodes_data {
    sbus_nodes_fn nodes_fn;
    void *handler_data;
};

static errno_t
sbus_nodes_hash_add(hash_table_t *table,
                    const char *object_path,
                    sbus_nodes_fn nodes_fn,
                    void *handler_data)
{
    TALLOC_CTX *tmp_ctx;
    struct sbus_nodes_data *data;
    hash_key_t key;
    hash_value_t value;
    errno_t ret;
    bool has_key;
    int hret;

    tmp_ctx = talloc_new(NULL);
    if (tmp_ctx == NULL) {
        return ENOMEM;
    }

    key.type = HASH_KEY_STRING;
    key.str = talloc_strdup(tmp_ctx, object_path);
    if (key.str == NULL) {
        return ENOMEM;
    }

    has_key = hash_has_key(table, &key);
    if (has_key) {
        ret = EEXIST;
        goto done;
    }

    data = talloc_zero(tmp_ctx, struct sbus_nodes_data);
    if (data == NULL) {
        ret = ENOMEM;
        goto done;
    }

    data->handler_data = handler_data;
    data->nodes_fn = nodes_fn;

    value.type = HASH_VALUE_PTR;
    value.ptr = data;

    hret = hash_enter(table, &key, &value);
    if (hret != HASH_SUCCESS) {
        ret = EIO;
        goto done;
    }

    talloc_steal(table, key.str);
    talloc_steal(table, data);

    ret = EOK;

done:
    talloc_free(tmp_ctx);
    return ret;
}

const char **
sbus_nodes_hash_lookup(TALLOC_CTX *mem_ctx,
                       hash_table_t *table,
                       const char *object_path)
{
    struct sbus_nodes_data *data;
    hash_key_t key;
    hash_value_t value;
    int hret;

    key.type = HASH_KEY_STRING;
    key.str = discard_const(object_path);

    hret = hash_lookup(table, &key, &value);
    if (hret == HASH_ERROR_KEY_NOT_FOUND) {
        return NULL;
    } else if (hret != HASH_SUCCESS) {
        DEBUG(SSSDBG_OP_FAILURE,
              "Unable to search hash table: hret=%d\n", hret);
        return NULL;
    }

    data = talloc_get_type(value.ptr, struct sbus_nodes_data);

    return data->nodes_fn(mem_ctx, object_path, data->handler_data);
}

static struct sbus_interface *
sbus_new_interface(TALLOC_CTX *mem_ctx,
                   const char *object_path,
                   struct sbus_vtable *iface_vtable,
                   void *handler_data)
{
    struct sbus_interface *intf;

    intf = talloc_zero(mem_ctx, struct sbus_interface);
    if (intf == NULL) {
        DEBUG(SSSDBG_FATAL_FAILURE, "Cannot allocate a new sbus_interface.\n");
        return NULL;
    }

    intf->path = talloc_strdup(intf, object_path);
    if (intf->path == NULL) {
        DEBUG(SSSDBG_FATAL_FAILURE, "Cannot duplicate object path.\n");
        talloc_free(intf);
        return NULL;
    }

    intf->vtable = iface_vtable;
    intf->handler_data = handler_data;
    return intf;
}

static DBusHandlerResult
sbus_message_handler(DBusConnection *dbus_conn,
                     DBusMessage *message,
                     void *user_data);

static errno_t
sbus_conn_register_path(struct sbus_connection *conn,
                        const char *path)
{
    static DBusObjectPathVTable vtable = {NULL, sbus_message_handler,
                                          NULL, NULL, NULL, NULL};
    DBusError error;
    char *reg_path = NULL;
    dbus_bool_t dbret;

    DEBUG(SSSDBG_TRACE_FUNC, "Registering object path %s with D-Bus "
          "connection\n", path);

    if (sbus_opath_is_subtree(path)) {
        reg_path = sbus_opath_get_base_path(conn, path);
        if (reg_path == NULL) {
            return ENOMEM;
        }

        /* D-Bus does not allow to have both object path and fallback
         * registered. Since we handle the real message handlers ourselves
         * we will register fallback only in this case. */
        if (sbus_opath_hash_has_path(conn->managed_paths, reg_path)) {
            dbus_connection_unregister_object_path(conn->dbus.conn, reg_path);
        }

        dbret = dbus_connection_register_fallback(conn->dbus.conn, reg_path,
                                                  &vtable, conn);
        talloc_free(reg_path);
    } else {
        dbus_error_init(&error);

        dbret = dbus_connection_try_register_object_path(conn->dbus.conn, path,
                                                         &vtable, conn, &error);

        if (dbus_error_is_set(&error) &&
                strcmp(error.name, DBUS_ERROR_OBJECT_PATH_IN_USE) == 0) {
            /* A fallback is probably already registered. Just return. */
            dbus_error_free(&error);
            return EOK;
        }
    }

    if (!dbret) {
        DEBUG(SSSDBG_FATAL_FAILURE, "Unable to register object path "
              "%s with D-Bus connection.\n", path);
        return ENOMEM;
    }

    return EOK;
}

errno_t
sbus_conn_register_iface(struct sbus_connection *conn,
                         struct sbus_vtable *iface_vtable,
                         const char *object_path,
                         void *handler_data)
{
    struct sbus_interface *iface = NULL;
    bool path_known;
    errno_t ret;

    if (conn == NULL || iface_vtable == NULL || object_path == NULL) {
        return EINVAL;
    }

    iface = sbus_new_interface(conn, object_path, iface_vtable, handler_data);
    if (iface == NULL) {
        return ENOMEM;
    }

    ret = sbus_opath_hash_add_iface(conn->managed_paths, object_path, iface,
                                    &path_known);
    if (ret != EOK) {
        talloc_free(iface);
        return ret;
    }

    if (path_known) {
        /* this object path is already registered */
        return EOK;
    }

    /* if ret != EOK we will still leave iface in the table, since
     * we probably don't have enough memory to remove it correctly anyway */

    ret = sbus_conn_register_path(conn, object_path);
    if (ret != EOK) {
        return ret;
    }

    /* register standard interfaces with this object path as well */
    ret = sbus_conn_register_iface(conn, sbus_properties_vtable(),
                                   object_path, conn);
    if (ret != EOK) {
        return ret;
    }

    ret = sbus_conn_register_iface(conn, sbus_introspect_vtable(),
                                   object_path, conn);
    if (ret != EOK) {
        return ret;
    }

    return ret;
}

void
sbus_conn_register_nodes(struct sbus_connection *conn,
                         const char *path,
                         sbus_nodes_fn nodes_fn,
                         void *data)
{
    errno_t ret;

    ret = sbus_nodes_hash_add(conn->nodes_fns, path, nodes_fn, data);
    if (ret != EOK && ret != EEXIST) {
        DEBUG(SSSDBG_MINOR_FAILURE, "Unable to register node function with "
              "%s. Introspection may not work correctly.\n", path);
    }
}

errno_t
sbus_conn_reregister_paths(struct sbus_connection *conn)
{
    hash_key_t *keys = NULL;
    unsigned long count;
    unsigned long i;
    errno_t ret;
    int hret;

    hret = hash_keys(conn->managed_paths, &count, &keys);
    if (hret != HASH_SUCCESS) {
        ret = ENOMEM;
        goto done;
    }

    for (i = 0; i < count; i++) {
        ret = sbus_conn_register_path(conn, keys[i].str);
        if (ret != EOK) {
            goto done;
        }
    }

    ret = EOK;

done:
    talloc_free(keys);
    return ret;
}

static void
sbus_message_handler_got_caller_id(struct tevent_req *req);

static DBusHandlerResult
sbus_message_handler(DBusConnection *dbus_conn,
                     DBusMessage *message,
                     void *handler_data)
{
    struct tevent_req *req;
    struct sbus_connection *conn;
    struct sbus_interface *iface;
    struct sbus_request *sbus_req;
    const struct sbus_method_meta *method;
    const char *iface_name;
    const char *method_name;
    const char *path;
    const char *sender;

    conn = talloc_get_type(handler_data, struct sbus_connection);

    /* header information */
    iface_name = dbus_message_get_interface(message);
    method_name = dbus_message_get_member(message);
    path = dbus_message_get_path(message);
    sender = dbus_message_get_sender(message);

    DEBUG(SSSDBG_TRACE_INTERNAL, "Received SBUS method %s.%s on path %s\n",
          iface_name, method_name, path);

    /* try to find the interface */
    iface = sbus_opath_hash_lookup_iface(conn->managed_paths,
                                         path, iface_name);
    if (iface == NULL) {
        goto fail;
    }

    method = sbus_meta_find_method(iface->vtable->meta, method_name);
    if (method == NULL || method->vtable_offset == 0) {
        goto fail;
    }

    /* we have a valid handler, create D-Bus request */
    sbus_req = sbus_new_request(conn, iface, message);
    if (sbus_req == NULL) {
        return DBUS_HANDLER_RESULT_NEED_MEMORY;
    }

    sbus_req->method = method;

    /* now get the sender ID */
    req = sbus_get_sender_id_send(sbus_req, conn->ev, conn, sender);
    if (req == NULL) {
        talloc_free(sbus_req);
        return DBUS_HANDLER_RESULT_NEED_MEMORY;
    }
    tevent_req_set_callback(req, sbus_message_handler_got_caller_id, sbus_req);

    return DBUS_HANDLER_RESULT_HANDLED;

fail: ;
    DBusMessage *reply;

    DEBUG(SSSDBG_CRIT_FAILURE, "No matching handler found for method %s.%s "
          "on path %s\n", iface_name, method_name, path);

    reply = dbus_message_new_error(message, DBUS_ERROR_UNKNOWN_METHOD, NULL);
    sbus_conn_send_reply(conn, reply);

    return DBUS_HANDLER_RESULT_HANDLED;
}

static void
sbus_message_handler_got_caller_id(struct tevent_req *req)
{
    struct sbus_request *sbus_req;
    const struct sbus_method_meta *method;
    sbus_msg_handler_fn handler;
    sbus_method_invoker_fn invoker;
    void *pvt;
    DBusError *error;
    errno_t ret;

    sbus_req = tevent_req_callback_data(req, struct sbus_request);
    method = sbus_req->method;

    ret = sbus_get_sender_id_recv(req, &sbus_req->client);
    if (ret != EOK) {
        error = sbus_error_new(sbus_req, DBUS_ERROR_FAILED, "Failed to "
                               "resolve caller's ID: %s\n", sss_strerror(ret));
        sbus_request_fail_and_finish(sbus_req, error);
        return;
    }

    handler = VTABLE_FUNC(sbus_req->intf->vtable, method->vtable_offset);
    invoker = method->invoker;
    pvt = sbus_req->intf->handler_data;

    sbus_request_invoke_or_finish(sbus_req, handler, pvt, invoker);
    return;
}