summaryrefslogtreecommitdiff
path: root/server/providers/data_provider.c
blob: 70b7cd3f5f75fb1bf8c9a13d65a4afcbb570ae06 (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
/*
   SSSD

   Data Provider

   Copyright (C) Simo Sorce <ssorce@redhat.com>	2008

   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 <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>
#include <security/pam_modules.h>

#include "popt.h"
#include "util/util.h"
#include "confdb/confdb.h"
#include "dbus/dbus.h"
#include "sbus/sssd_dbus.h"
#include "data_provider.h"
#include "dp_interfaces.h"
#include "monitor/monitor_interfaces.h"

struct dp_backend;
struct dp_frontend;

struct dp_ctx {
    struct tevent_context *ev;
    struct confdb_ctx *cdb;
    struct sbus_connection *sbus_srv;
    struct dp_backend *be_list;
    struct dp_frontend *fe_list;
};

struct dp_client {
    struct dp_ctx *dpctx;
    struct sbus_connection *conn;
    struct tevent_timer *timeout;
    bool initialized;
};

struct dp_backend {
    struct dp_backend *prev;
    struct dp_backend *next;
    char *domain;
    struct dp_client *dpcli;
};

struct dp_frontend {
    struct dp_frontend *prev;
    struct dp_frontend *next;
    char *name;
    uint16_t flags;
    struct dp_client *dpcli;
};

static int dp_backend_destructor(void *ctx);
static int dp_frontend_destructor(void *ctx);

static int service_reload(DBusMessage *message, struct sbus_connection *conn);

struct sbus_method monitor_dp_methods[] = {
    { MON_CLI_METHOD_PING, monitor_common_pong },
    { MON_CLI_METHOD_RELOAD, service_reload },
    { MON_CLI_METHOD_RES_INIT, monitor_common_res_init },
    { NULL, NULL }
};

struct sbus_interface monitor_dp_interface = {
    MONITOR_INTERFACE,
    MONITOR_PATH,
    SBUS_DEFAULT_VTABLE,
    monitor_dp_methods,
    NULL
};

static int client_registration(DBusMessage *message,
                               struct sbus_connection *conn);
static int dp_get_account_info(DBusMessage *message,
                               struct sbus_connection *conn);
static int dp_pamhandler(DBusMessage *message, struct sbus_connection *conn);

struct sbus_method dp_methods[] = {
    { DP_SRV_METHOD_REGISTER, client_registration },
    { DP_SRV_METHOD_GETACCTINFO, dp_get_account_info },
    { DP_SRV_METHOD_PAMHANDLER, dp_pamhandler },
    { NULL, NULL }
};

struct sbus_interface dp_interface = {
    DP_SRV_INTERFACE,
    DP_SRV_PATH,
    SBUS_DEFAULT_VTABLE,
    dp_methods,
    NULL
};

struct dp_request {
    /* reply message to send when request is done */
    DBusMessage *reply;
    /* frontend client that made the request */
    struct dp_client *src_cli;

    int pending_replies;
};

struct dp_be_request {
    struct dp_request *req;
    struct dp_backend *be;
};

static int service_reload(DBusMessage *message, struct sbus_connection *conn)
{
    /* Monitor calls this function when we need to reload
     * our configuration information. Perform whatever steps
     * are needed to update the configuration objects.
     */

    /* Send an empty reply to acknowledge receipt */
    return monitor_common_pong(message, conn);
}

static int dp_monitor_init(struct dp_ctx *dpctx)
{
    struct sbus_connection *conn;
    char *sbus_address;
    int ret;

    /* Set up SBUS connection to the monitor */
    ret = monitor_get_sbus_address(dpctx, &sbus_address);
    if (ret != EOK) {
        DEBUG(0, ("Could not locate monitor address.\n"));
        return ret;
    }

    ret = sbus_client_init(dpctx, dpctx->ev, sbus_address,
                           &monitor_dp_interface, &conn,
                           NULL, NULL);
    if (ret != EOK) {
        DEBUG(0, ("Failed to connect to monitor services.\n"));
        return ret;
    }

    /* Identify ourselves to the monitor */
    ret = monitor_common_send_id(conn,
                                 DATA_PROVIDER_SERVICE_NAME,
                                 DATA_PROVIDER_VERSION);
    if (ret != EOK) {
        DEBUG(0, ("Failed to identify to the monitor!\n"));
        return ret;
    }

    return EOK;
}

static void init_timeout(struct tevent_context *ev,
                         struct tevent_timer *te,
                         struct timeval t, void *ptr)
{
    struct dp_client *dpcli;

    DEBUG(2, ("Client timed out before Identification [%p]!\n", te));

    dpcli = talloc_get_type(ptr, struct dp_client);

    sbus_disconnect(dpcli->conn);
    talloc_zfree(dpcli);
}

static int dp_client_init(struct sbus_connection *conn, void *data)
{
    struct dp_ctx *dpctx;
    struct dp_client *dpcli;
    struct timeval tv;

    dpctx = talloc_get_type(data, struct dp_ctx);

    /* hang off this memory to the connection so that when the connection
     * is freed we can potentially call a destructor */

    dpcli = talloc(conn, struct dp_client);
    if (!dpcli) {
        DEBUG(0,("Out of memory?!\n"));
        talloc_zfree(conn);
        return ENOMEM;
    }
    dpcli->dpctx = dpctx;
    dpcli->conn = conn;
    dpcli->initialized = false;

    /* 5 seconds should be plenty */
    tv = tevent_timeval_current_ofs(5, 0);

    dpcli->timeout = tevent_add_timer(dpctx->ev, dpcli,
                                      tv, init_timeout, dpcli);
    if (!dpcli->timeout) {
        DEBUG(0,("Out of memory?!\n"));
        talloc_zfree(conn);
        return ENOMEM;
    }
    DEBUG(4, ("Set-up DP ID timeout [%p]\n", dpcli->timeout));

    /* Attach the client context to the connection context, so that it is
     * always available when we need to manage the connection. */
    sbus_conn_set_private_data(conn, dpcli);

    return EOK;
}

static int client_registration(DBusMessage *message,
                               struct sbus_connection *conn)
{
    dbus_uint16_t version = DATA_PROVIDER_VERSION;
    struct dp_backend *dpbe;
    struct dp_frontend *dpfe;
    struct dp_client *dpcli;
    DBusMessage *reply;
    DBusError dbus_error;
    dbus_uint16_t cli_ver;
    dbus_uint16_t cli_type;
    char *cli_name;
    char *cli_domain;
    dbus_bool_t dbret;
    void *data;

    data = sbus_conn_get_private_data(conn);
    dpcli = talloc_get_type(data, struct dp_client);
    if (!dpcli) {
        DEBUG(0, ("Connection holds no valid init data\n"));
        return EINVAL;
    }

    /* First thing, cancel the timeout */
    DEBUG(4, ("Cancel DP ID timeout [%p]\n", dpcli->timeout));
    talloc_zfree(dpcli->timeout);

    dbus_error_init(&dbus_error);

    dbret = dbus_message_get_args(message, &dbus_error,
                                  DBUS_TYPE_UINT16, &cli_type,
                                  DBUS_TYPE_UINT16, &cli_ver,
                                  DBUS_TYPE_STRING, &cli_name,
                                  DBUS_TYPE_STRING, &cli_domain,
                                  DBUS_TYPE_INVALID);
    if (!dbret) {
        DEBUG(1, ("Failed to parse message, killing connection\n"));
        if (dbus_error_is_set(&dbus_error)) dbus_error_free(&dbus_error);
        sbus_disconnect(conn);
        /* FIXME: should we just talloc_zfree(conn) ? */
        return EIO;
    }

    switch (cli_type & DP_CLI_TYPE_MASK) {
    case DP_CLI_BACKEND:
        dpbe = talloc_zero(dpcli->dpctx, struct dp_backend);
        if (!dpbe) {
            DEBUG(0, ("Out of memory!\n"));
            sbus_disconnect(conn);
            return ENOMEM;
        }

        dpbe->domain = talloc_strdup(dpbe, cli_domain);
        if (!dpbe->domain) {
            DEBUG(0, ("Out of memory!\n"));
            sbus_disconnect(conn);
            return ENOMEM;
        }

        dpbe->dpcli = dpcli;

        DLIST_ADD(dpcli->dpctx->be_list, dpbe);

        DEBUG(4, ("Added Backend client for domain [%s]\n", dpbe->domain));

        talloc_set_destructor((TALLOC_CTX *)dpbe, dp_backend_destructor);
        break;

    case DP_CLI_FRONTEND:
        dpfe = talloc_zero(dpcli->dpctx, struct dp_frontend);
        if (!dpfe) {
            DEBUG(0, ("Out of memory!\n"));
            sbus_disconnect(conn);
            return ENOMEM;
        }

        dpfe->name = talloc_strdup(dpfe, cli_name);
        if (!dpfe->name) {
            DEBUG(0, ("Out of memory!\n"));
            sbus_disconnect(conn);
            return ENOMEM;
        }

        dpfe->dpcli = dpcli;

        DLIST_ADD(dpcli->dpctx->fe_list, dpfe);

        DEBUG(4, ("Added Frontend client [%s]\n", dpfe->name));

        talloc_set_destructor((TALLOC_CTX *)dpfe, dp_frontend_destructor);
        break;

    default:
        DEBUG(1, ("Unknown client type, killing connection\n"));
        sbus_disconnect(conn);
        return EIO;
    }

    /* reply that all is ok */
    reply = dbus_message_new_method_return(message);
    if (!reply) {
        DEBUG(0, ("Dbus Out of memory!\n"));
        return ENOMEM;
    }

    dbret = dbus_message_append_args(reply,
                                     DBUS_TYPE_UINT16, &version,
                                     DBUS_TYPE_INVALID);
    if (!dbret) {
        DEBUG(0, ("Failed to build dbus reply\n"));
        dbus_message_unref(reply);
        sbus_disconnect(conn);
        return EIO;
    }

    /* send reply back */
    sbus_conn_send_reply(conn, reply);
    dbus_message_unref(reply);

    dpcli->initialized = true;
    return EOK;
}

static void be_got_account_info(DBusPendingCall *pending, void *data)
{
    struct dp_be_request *bereq;
    DBusMessage *reply;
    DBusConnection *dbus_conn;
    DBusError dbus_error;
    dbus_uint16_t err_maj = 0;
    dbus_uint32_t err_min = 0;
    const char *err_msg;
    dbus_bool_t ret;
    int type;

    bereq = talloc_get_type(data, struct dp_be_request);
    dbus_error_init(&dbus_error);

    reply = dbus_pending_call_steal_reply(pending);
    if (!reply) {
        /* reply should never be null. This function shouldn't be called
         * until reply is valid or timeout has occurred. If reply is NULL
         * here, something is seriously wrong and we should bail out.
         */
        DEBUG(0, ("Severe error. A reply callback was called but no reply was received and no timeout occurred\n"));

        /* Destroy this connection */
        sbus_disconnect(bereq->be->dpcli->conn);
        goto done;
    }

    type = dbus_message_get_type(reply);
    switch (type) {
    case DBUS_MESSAGE_TYPE_METHOD_RETURN:
        ret = dbus_message_get_args(reply, &dbus_error,
                                    DBUS_TYPE_UINT16, &err_maj,
                                    DBUS_TYPE_UINT32, &err_min,
                                    DBUS_TYPE_STRING, &err_msg,
                                    DBUS_TYPE_INVALID);
        if (!ret) {
            DEBUG(1,("Failed to parse message, killing connection\n"));
            if (dbus_error_is_set(&dbus_error)) dbus_error_free(&dbus_error);
            sbus_disconnect(bereq->be->dpcli->conn);
            goto done;
        }

        DEBUG(4, ("Got reply (%u, %u, %s) from (%s)\n",
                  (unsigned int)err_maj, (unsigned int)err_min, err_msg,
                  bereq->be->domain));

        break;

    case DBUS_MESSAGE_TYPE_ERROR:
        DEBUG(0,("The Data Provider returned an error [%s], closing connection.\n",
                 dbus_message_get_error_name(reply)));
        /* Falling through to default intentionally*/
    default:
        /*
         * Timeout or other error occurred or something
         * unexpected happened.
         * It doesn't matter which, because either way we
         * know that this connection isn't trustworthy.
         * We'll destroy it now.
         */
        sbus_disconnect(bereq->be->dpcli->conn);
    }

    if (err_maj) {
        DEBUG(1, ("Backend returned an error: %d,%d(%s),%s\n",
                  err_maj, err_min, strerror(err_min), err_msg));
        /* TODO: handle errors !! */
    }

    if (bereq->req->pending_replies > 1) {
        bereq->req->pending_replies--;
        talloc_free(bereq);
    } else {
        dbus_conn = sbus_get_connection(bereq->req->src_cli->conn);
        err_maj = 0;
        err_min = 0;
        err_msg = "Success";
        ret = dbus_message_append_args(bereq->req->reply,
                                       DBUS_TYPE_UINT16, &err_maj,
                                       DBUS_TYPE_UINT32, &err_min,
                                       DBUS_TYPE_STRING, &err_msg,
                                       DBUS_TYPE_INVALID);
        if (!ret) {
            DEBUG(1, ("Failed to build reply ... frontend will wait for timeout ...\n"));
            talloc_free(bereq->req);
            goto done;
        }

        /* finally send it */
        dbus_connection_send(dbus_conn, bereq->req->reply, NULL);
        dbus_message_unref(bereq->req->reply);
        talloc_free(bereq->req);
    }

done:
    dbus_pending_call_unref(pending);
    dbus_message_unref(reply);
}

static int dp_send_acct_req(struct dp_be_request *bereq,
                            uint32_t type, char *attrs, char *filter)
{
    DBusMessage *msg;
    DBusPendingCall *pending_reply;
    DBusConnection *dbus_conn;
    dbus_bool_t ret;

    dbus_conn = sbus_get_connection(bereq->be->dpcli->conn);

    /* create the message */
    msg = dbus_message_new_method_call(NULL,
                                       DP_CLI_PATH,
                                       DP_CLI_INTERFACE,
                                       DP_CLI_METHOD_GETACCTINFO);
    if (msg == NULL) {
        DEBUG(0,("Out of memory?!\n"));
        return ENOMEM;
    }

    DEBUG(4, ("Sending request for [%u][%s][%s]\n", type, attrs, filter));

    ret = dbus_message_append_args(msg,
                                   DBUS_TYPE_UINT32, &type,
                                   DBUS_TYPE_STRING, &attrs,
                                   DBUS_TYPE_STRING, &filter,
                                   DBUS_TYPE_INVALID);
    if (!ret) {
        DEBUG(1,("Failed to build message\n"));
        return EIO;
    }

    ret = dbus_connection_send_with_reply(dbus_conn, msg, &pending_reply,
                                            600000 /* TODO: set timeout */);
    if (!ret || pending_reply == NULL) {
        /*
         * Critical Failure
         * We can't communicate on this connection
         * We'll drop it using the default destructor.
         */
        DEBUG(0, ("D-BUS send failed.\n"));
        dbus_message_unref(msg);
        return EIO;
    }

    /* Set up the reply handler */
    dbus_pending_call_set_notify(pending_reply, be_got_account_info,
                                 bereq, NULL);
    dbus_message_unref(msg);

    return EOK;
}

static int dp_get_account_info(DBusMessage *message, struct sbus_connection *conn)
{
    struct dp_client *dpcli;
    struct dp_be_request *bereq;
    struct dp_request *dpreq = NULL;
    struct dp_backend *dpbe;
    DBusMessage *reply;
    DBusError dbus_error;
    dbus_bool_t dbret;
    void *user_data;
    uint32_t type;
    char *domain, *attrs, *filter;
    const char *errmsg = NULL;
    int dpret = 0, ret = 0;

    user_data = sbus_conn_get_private_data(conn);
    if (!user_data) return EINVAL;
    dpcli = talloc_get_type(user_data, struct dp_client);
    if (!dpcli) return EINVAL;

    dbus_error_init(&dbus_error);

    ret = dbus_message_get_args(message, &dbus_error,
                                DBUS_TYPE_STRING, &domain,
                                DBUS_TYPE_UINT32, &type,
                                DBUS_TYPE_STRING, &attrs,
                                DBUS_TYPE_STRING, &filter,
                                DBUS_TYPE_INVALID);
    if (!ret) {
        DEBUG(1,("Failed, to parse message!\n"));
        if (dbus_error_is_set(&dbus_error)) dbus_error_free(&dbus_error);
        return EIO;
    }

    DEBUG(4, ("Got request for [%s][%u][%s][%s]\n",
              domain, type, attrs, filter));

    reply = dbus_message_new_method_return(message);
    if (!reply) return ENOMEM;

    /* search for domain */
    if (!domain) {
        dpret = DP_ERR_FATAL;
        errmsg = "Invalid Domain";
        ret = EINVAL;
        goto respond;
    }

    /* all domains, fire off a request for each backend */
    if (strcmp(domain, "*") == 0) {
        dpreq = talloc(dpcli->dpctx, struct dp_request);
        if (!dpreq) {
            dpret = DP_ERR_FATAL;
            errmsg = "Out of memory";
            ret = ENOMEM;
            goto respond;
        }

        dpreq->reply = reply;
        dpreq->src_cli = dpcli;
        dpreq->pending_replies = 0;

        /* now fire off requests */
        dpbe = dpcli->dpctx->be_list;
        while (dpbe) {
            bereq = talloc(dpreq, struct dp_be_request);
            if (!bereq) {
                DEBUG(1, ("Out of memory while sending requests\n"));
                dpbe = dpbe->next;
                continue;
            }
            bereq->req = dpreq;
            bereq->be = dpbe;
            DEBUG(4, ("Sending wildcard request to [%s]\n", dpbe->domain));
            ret = dp_send_acct_req(bereq, type, attrs, filter);
            if (ret != EOK) {
                DEBUG(2,("Failed to dispatch request to %s\n", dpbe->domain));
                dpbe = dpbe->next;
                continue;
            }
            dpreq->pending_replies++;
            dpbe = dpbe->next;
        }

        if (dpreq->pending_replies == 0) {
            dpret = DP_ERR_FATAL;
            errmsg = "Unable to contact backends";
            ret = EIO;
            talloc_free(dpreq);
            goto respond;
        }

        return EOK;
    }

    dpbe = dpcli->dpctx->be_list;
    while (dpbe) {
        if (strcasecmp(dpbe->domain, domain) == 0) {
            break;
        }

        dpbe = dpbe->next;
    }

    if (dpbe) {
        dpreq = talloc(dpcli->dpctx, struct dp_request);
        if (!dpreq) {
            DEBUG(1, ("Out of memory while sending request\n"));
            dpret = DP_ERR_FATAL;
            errmsg = "Out of memory";
            ret = ENOMEM;
            goto respond;
        }

        dpreq->reply = reply;
        dpreq->src_cli = dpcli;
        dpreq->pending_replies = 1;

        bereq = talloc(dpreq, struct dp_be_request);
        if (!bereq) {
            DEBUG(1, ("Out of memory while sending request\n"));
            dpret = DP_ERR_FATAL;
            errmsg = "Out of memory";
            ret = ENOMEM;
            talloc_free(dpreq);
            goto respond;
        }
        bereq->req = dpreq;
        bereq->be = dpbe;

        ret = dp_send_acct_req(bereq, type, attrs, filter);
        if (ret != EOK) {
            DEBUG(2,("Failed to dispatch request to %s\n", dpbe->domain));
            dpret = DP_ERR_FATAL;
            errmsg = "Dispatch Failed";
            talloc_free(dpreq);
            goto respond;
        }

    } else {

        dpret = DP_ERR_FATAL;
        errmsg = "Invalid Domain";
        ret = EINVAL;
        goto respond;
    }

    return EOK;

respond:
    dbret = dbus_message_append_args(reply,
                                     DBUS_TYPE_UINT16, &dpret,
                                     DBUS_TYPE_UINT32, &ret,
                                     DBUS_TYPE_STRING, &errmsg,
                                     DBUS_TYPE_INVALID);
    if (!dbret) return EIO;

    /* send reply back immediately */
    sbus_conn_send_reply(conn, reply);
    dbus_message_unref(reply);

    return EOK;
}

static void be_got_pam_reply(DBusPendingCall *pending, void *data)
{
    struct dp_be_request *bereq;
    DBusMessage *reply;
    DBusConnection *dbus_conn;
    DBusError dbus_error;
    dbus_bool_t ret;
    struct pam_data *pd = NULL;
    int type;

    bereq = talloc_get_type(data, struct dp_be_request);
    dbus_error_init(&dbus_error);

    reply = dbus_pending_call_steal_reply(pending);
    if (!reply) {
        /* reply should never be null. This function shouldn't be called
         * until reply is valid or timeout has occurred. If reply is NULL
         * here, something is seriously wrong and we should bail out.
         */
        DEBUG(0, ("Severe error. A reply callback was called but no reply was received and no timeout occurred\n"));

        /* Destroy this connection */
        sbus_disconnect(bereq->be->dpcli->conn);
        goto done;
    }

    pd = talloc_zero(bereq, struct pam_data);
    type = dbus_message_get_type(reply);
    switch (type) {
    case DBUS_MESSAGE_TYPE_METHOD_RETURN:
        ret = dp_unpack_pam_response(reply, pd, &dbus_error);
        if (!ret) {
            DEBUG(1,("Failed to parse message, killing connection\n"));
            if (dbus_error_is_set(&dbus_error)) dbus_error_free(&dbus_error);
            sbus_disconnect(bereq->be->dpcli->conn);
            pd->pam_status = PAM_SYSTEM_ERR;
            pd->domain = talloc_strdup(pd, "");
            goto done;
        }

        DEBUG(4, ("Got reply (%d, %s) from (%s)\n", pd->pam_status, pd->domain,
                  bereq->be->domain));

        break;

    case DBUS_MESSAGE_TYPE_ERROR:
        DEBUG(0,("The Data Provider returned an error [%s], closing connection.\n",
                 dbus_message_get_error_name(reply)));
        /* Falling through to default intentionally*/
    default:
        /*
         * Timeout or other error occurred or something
         * unexpected happened.
         * It doesn't matter which, because either way we
         * know that this connection isn't trustworthy.
         * We'll destroy it now.
         */
        DEBUG(1,("Maybe timeout?\n"));
        sbus_disconnect(bereq->be->dpcli->conn);
        goto done;
    }

    dbus_conn = sbus_get_connection(bereq->req->src_cli->conn);

    ret = dp_pack_pam_response(bereq->req->reply, pd);
    if (!ret) {
        DEBUG(1, ("Failed to build reply ... frontend will wait for timeout ...\n"));
        talloc_free(bereq->req);
        goto done;
    }

    /* finally send it */
    dbus_connection_send(dbus_conn, bereq->req->reply, NULL);
    dbus_message_unref(bereq->req->reply);
    talloc_free(bereq->req);

done:
    dbus_pending_call_unref(pending);
    dbus_message_unref(reply);
}

static int dp_call_pamhandler(struct dp_be_request *bereq, struct pam_data *pd)
{
    DBusMessage *msg;
    DBusPendingCall *pending_reply;
    DBusConnection *dbus_conn;
    dbus_bool_t ret;

    dbus_conn = sbus_get_connection(bereq->be->dpcli->conn);

    /* create the message */
    msg = dbus_message_new_method_call(NULL,
                                       DP_CLI_PATH,
                                       DP_CLI_INTERFACE,
                                       DP_CLI_METHOD_PAMHANDLER);
    if (msg == NULL) {
        DEBUG(0,("Out of memory?!\n"));
        return ENOMEM;
    }

    DEBUG(4, ("Sending request with to following data\n"));
    DEBUG_PAM_DATA(4, pd);

    ret = dp_pack_pam_request(msg, pd);
    if (!ret) {
        DEBUG(1,("Failed to build message\n"));
        return EIO;
    }

    ret = dbus_connection_send_with_reply(dbus_conn, msg, &pending_reply,
                                          600000 /* TODO: set timeout */);
    if (!ret || pending_reply == NULL) {
        /*
         * Critical Failure
         * We can't communicate on this connection
         * We'll drop it using the default destructor.
         */
        DEBUG(0, ("D-BUS send failed.\n"));
        dbus_message_unref(msg);
        return EIO;
    }

    /* Set up the reply handler */
    dbus_pending_call_set_notify(pending_reply, be_got_pam_reply,
                                 bereq, NULL);
    dbus_message_unref(msg);

    return EOK;
}

static int dp_pamhandler(DBusMessage *message, struct sbus_connection *conn)
{
    DBusMessage *reply;
    DBusError dbus_error;
    struct dp_client *dpcli;
    struct dp_backend *dpbe;
    struct dp_be_request *bereq;
    struct dp_request *dpreq = NULL;
    dbus_bool_t dbret;
    void *user_data;
    int ret;
    struct pam_data *pd;
    int pam_status=PAM_SUCCESS;
    int domain_found=0;

    user_data = sbus_conn_get_private_data(conn);
    if (!user_data) return EINVAL;
    dpcli = talloc_get_type(user_data, struct dp_client);
    if (!dpcli) return EINVAL;

/* FIXME: free arrays returned by dbus_message_get_args() */
    pd = talloc(NULL, struct pam_data);
    if (!pd) return ENOMEM;

    dbus_error_init(&dbus_error);

    ret = dp_unpack_pam_request(message, pd, &dbus_error);
    if (!ret) {
        DEBUG(0,("Failed, to parse message!\n"));
        if (dbus_error_is_set(&dbus_error)) dbus_error_free(&dbus_error);
        talloc_free(pd);
        return EIO;
    }

    DEBUG(4, ("Got the following data:\n"));
    DEBUG_PAM_DATA(4, pd);

    reply = dbus_message_new_method_return(message);
    if (!reply) {
        DEBUG(0,("Out of memory?!\n"));
        talloc_free(pd);
        return ENOMEM;
    }

    dpreq = talloc(dpcli->dpctx, struct dp_request);
    if (!dpreq) {
        ret = ENOMEM;
        pam_status = PAM_ABORT;
        goto respond;
    }

    dpreq->reply = reply;
    dpreq->src_cli = dpcli;
    dpreq->pending_replies = 0;
    /* FIXME: add handling of default domain */
    dpbe = dpcli->dpctx->be_list;
    while (dpbe) {
        DEBUG(4, ("Checking [%s][%s]\n", pd->domain, dpbe->domain));
        if (strcasecmp(dpbe->domain, pd->domain) == 0 ) {
            domain_found=1;
            bereq = talloc(dpreq, struct dp_be_request);
            if (!bereq) {
                DEBUG(1, ("Out of memory while sending requests\n"));
                dpbe = dpbe->next;
                continue;
            }
            bereq->req = dpreq;
            bereq->be = dpbe;
            DEBUG(4, ("Sending wildcard request to [%s]\n", dpbe->domain));
            ret = dp_call_pamhandler(bereq, pd);
            if (ret != EOK) {
                DEBUG(2,("Failed to dispatch request to %s\n", dpbe->domain));
                dpbe = dpbe->next;
                continue;
            }
            dpreq->pending_replies++;
        }
        dpbe = dpbe->next;
    }

    if (domain_found) {
        talloc_free(pd);
        return EOK;
    }

    pam_status = PAM_MODULE_UNKNOWN;

respond:
    dbret = dbus_message_append_args(reply,
                                     DBUS_TYPE_UINT32, &pam_status,
                                     DBUS_TYPE_STRING, &(pd->domain),
                                     DBUS_TYPE_INVALID);
    if (!dbret) return EIO;

    /* send reply back immediately */
    sbus_conn_send_reply(conn, reply);
    dbus_message_unref(reply);

    talloc_free(pd);
    return EOK;
}

static int dp_backend_destructor(void *ctx)
{
    struct dp_backend *dpbe = talloc_get_type(ctx, struct dp_backend);
    if (dpbe->dpcli && dpbe->dpcli->dpctx && dpbe->dpcli->dpctx->be_list) {
        DLIST_REMOVE(dpbe->dpcli->dpctx->be_list, dpbe);
        DEBUG(4, ("Removed Backend client for domain [%s]\n",
                  dpbe->domain));
    }
    return 0;
}

static int dp_frontend_destructor(void *ctx)
{
    struct dp_frontend *dpfe = talloc_get_type(ctx, struct dp_frontend);
    if (dpfe->dpcli && dpfe->dpcli->dpctx && dpfe->dpcli->dpctx->fe_list) {
        DLIST_REMOVE(dpfe->dpcli->dpctx->fe_list, dpfe);
        DEBUG(4, ("Removed Frontend client [%s]\n", dpfe->name));
    }
    return 0;
}

/* monitor_dbus_init
 * Set up the monitor service as a D-BUS Server */
static int dp_srv_init(struct dp_ctx *dpctx)
{
    char *dpbus_address;
    int ret;

    DEBUG(3, ("Initializing Data Provider D-BUS Server\n"));
    ret = dp_get_sbus_address(dpctx, &dpbus_address);

    ret = sbus_new_server(dpctx, dpctx->ev, dpbus_address,
                          &dp_interface, &dpctx->sbus_srv,
                          dp_client_init, dpctx);
    return ret;
}

static int dp_process_init(TALLOC_CTX *mem_ctx,
                           struct tevent_context *ev,
                           struct confdb_ctx *cdb)
{
    struct dp_ctx *dpctx;
    int ret;

    dpctx = talloc_zero(mem_ctx, struct dp_ctx);
    if (!dpctx) {
        DEBUG(0, ("fatal error initializing dp_ctx\n"));
        return ENOMEM;
    }
    dpctx->ev = ev;
    dpctx->cdb = cdb;

    ret = dp_monitor_init(dpctx);
    if (ret != EOK) {
        DEBUG(0, ("fatal error setting up monitor bus\n"));
        return ret;
    }

    ret = dp_srv_init(dpctx);
    if (ret != EOK) {
        DEBUG(0, ("fatal error setting up server bus\n"));
        return ret;
    }

    return EOK;
}

int main(int argc, const char *argv[])
{
    int opt;
    poptContext pc;
    struct main_context *main_ctx;
    int ret;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
        SSSD_MAIN_OPTS
		{ NULL }
	};

	pc = poptGetContext(argv[0], argc, argv, long_options, 0);
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch(opt) {
		default:
			fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			return 1;
		}
	}

	poptFreeContext(pc);

    /* set up things like debug, signals, daemonization, etc... */
    debug_log_file = "sssd_dp";

    ret = server_setup("sssd[dp]", 0, CONFDB_DP_CONF_ENTRY, &main_ctx);
    if (ret != EOK) return 2;

    ret = die_if_parent_died();
    if (ret != EOK) {
        /* This is not fatal, don't return */
        DEBUG(2, ("Could not set up to exit when parent process does\n"));
    }

    ret = dp_process_init(main_ctx,
                           main_ctx->event_ctx,
                           main_ctx->confdb_ctx);
    if (ret != EOK) return 3;

    /* loop on main */
    server_loop(main_ctx);

    return 0;
}