summaryrefslogtreecommitdiff
path: root/server/monitor/monitor.c
blob: 2a444dc6f2969504e5cd9283d01e7175e0f300ff (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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
/*
   SSSD

   Service monitor

   Copyright (C) Simo Sorce			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/>.
*/

#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/param.h>
#include <time.h>
#include <string.h>
#include "config.h"
#ifdef HAVE_SYS_INOTIFY_H
#include <sys/inotify.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "util/util.h"
#include "popt.h"
#include "tevent.h"
#include "confdb/confdb.h"
#include "confdb/confdb_setup.h"
#include "collection.h"
#include "ini_config.h"
#include "db/sysdb.h"
#include "monitor/monitor.h"
#include "dbus/dbus.h"
#include "sbus/sssd_dbus.h"
#include "monitor/monitor_interfaces.h"

/* ping time cannot be less then once every few seconds or the
 * monitor will get crazy hammering children with messages */
#define MONITOR_DEF_PING_TIME 10
#define MONITOR_CONF_ENTRY "config/services/monitor"

struct mt_conn {
    struct sbus_conn_ctx *conn_ctx;
    struct mt_svc *svc_ptr;
};

struct mt_svc {
    struct mt_svc *prev;
    struct mt_svc *next;

    struct mt_conn *mt_conn;
    struct mt_ctx *mt_ctx;

    char *provider;
    char *command;
    char *name;
    char *identity;
    pid_t pid;

    int ping_time;

    int restarts;
    time_t last_restart;
    time_t last_pong;

    int debug_level;

    struct tevent_timer *ping_ev;
};

struct mt_ctx {
    struct tevent_context *ev;
    struct confdb_ctx *cdb;
    TALLOC_CTX *domain_ctx; /* Memory context for domain list */
    struct sss_domain_info *domains;
    TALLOC_CTX *service_ctx; /* Memory context for services */
    char **services;
    struct mt_svc *svc_list;
    struct sbus_srv_ctx *sbus_srv;

    int service_id_timeout;
};

struct config_file_ctx {
    TALLOC_CTX *parent_ctx;
    struct confdb_ctx *cdb;
    struct tevent_context *ev;
    int fd;
    char *filename;
    time_t modified;
    confdb_reconf_fn reconf_fn;
    void *reconf_pvt;
};

static int start_service(struct mt_svc *mt_svc);

static int dbus_service_init(struct sbus_conn_ctx *conn_ctx, void *data);
static void identity_check(DBusPendingCall *pending, void *data);

static int service_send_ping(struct mt_svc *svc);
static void ping_check(DBusPendingCall *pending, void *data);

static int service_check_alive(struct mt_svc *svc);

static void set_tasks_checker(struct mt_svc *srv);
static void set_global_checker(struct mt_ctx *ctx);
static int monitor_kill_service (struct mt_svc *svc);

static int get_service_config(struct mt_ctx *ctx, const char *name,
                              struct mt_svc **svc_cfg);
static int get_provider_config(struct mt_ctx *ctx, const char *name,
                              struct mt_svc **svc_cfg);
static int add_new_service(struct mt_ctx *ctx, const char *name);
static int add_new_provider(struct mt_ctx *ctx, const char *name);

static int monitor_signal_reconf(struct confdb_ctx *cdb, void *pvt);
static int update_monitor_config(struct mt_ctx *ctx);
static int monitor_cleanup(void);

/* dbus_get_monitor_version
 * Return the monitor version over D-BUS */
static int dbus_get_monitor_version(DBusMessage *message,
                                    struct sbus_conn_ctx *sconn)
{
    const char *version = MONITOR_VERSION;
    DBusMessage *reply;
    dbus_bool_t ret;

    reply = dbus_message_new_method_return(message);
    if (!reply) return ENOMEM;
    ret = dbus_message_append_args(reply, DBUS_TYPE_STRING,
                                   &version, DBUS_TYPE_INVALID);
    if (!ret) {
        dbus_message_unref(reply);
        return EIO;
    }

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

    return EOK;
}

struct sbus_method monitor_methods[] = {
    { MONITOR_METHOD_VERSION, dbus_get_monitor_version},
    {NULL, NULL}
};

/* monitor_dbus_init
 * Set up the monitor service as a D-BUS Server */
static int monitor_dbus_init(struct mt_ctx *ctx)
{
    struct sbus_method_ctx *sd_ctx;
    struct sbus_srv_ctx *sbus_srv;
    char *monitor_address;
    int ret;

    sd_ctx = talloc_zero(ctx, struct sbus_method_ctx);
    if (!sd_ctx) {
        return ENOMEM;
    }

    monitor_address = talloc_asprintf(sd_ctx, "unix:path=%s/%s",
                                      PIPE_PATH, SSSD_SERVICE_PIPE);
    if (!monitor_address) {
        talloc_free(sd_ctx);
        return ENOMEM;
    }

    /* Set up globally-available D-BUS methods */
    sd_ctx->interface = talloc_strdup(sd_ctx, MONITOR_DBUS_INTERFACE);
    if (!sd_ctx->interface) {
        talloc_free(sd_ctx);
        return ENOMEM;
    }
    sd_ctx->path = talloc_strdup(sd_ctx, MONITOR_DBUS_PATH);
    if (!sd_ctx->path) {
        talloc_free(sd_ctx);
        return ENOMEM;
    }
    sd_ctx->methods = monitor_methods;
    sd_ctx->message_handler = sbus_message_handler;

    ret = sbus_new_server(ctx, ctx->ev, sd_ctx, &sbus_srv, monitor_address, dbus_service_init, ctx);
    ctx->sbus_srv = sbus_srv;

    talloc_free(monitor_address);

    return ret;
}

static void svc_try_restart(struct mt_svc *svc, time_t now)
{
    int ret;

    DLIST_REMOVE(svc->mt_ctx->svc_list, svc);
    if (svc->last_restart != 0) {
        if ((now - svc->last_restart) > 30) { /* TODO: get val from config */
            /* it was long ago reset restart threshold */
            svc->restarts = 0;
        }
    }

    /* restart the process */
    if (svc->restarts > 3) { /* TODO: get val from config */
        DEBUG(0, ("Process [%s], definitely stopped!\n", svc->name));
        talloc_free(svc);
        return;
    }

    /* Shut down the current ping timer so it will restart
     * cleanly in start_service()
     */
    talloc_free(svc->ping_ev);

    ret = start_service(svc);
    if (ret != EOK) {
        DEBUG(0,("Failed to restart service '%s'\n", svc->name));
        talloc_free(svc);
        return;
    }

    svc->restarts++;
    svc->last_restart = now;
    return;
}

static void tasks_check_handler(struct tevent_context *ev,
                                struct tevent_timer *te,
                                struct timeval t, void *ptr)
{
    struct mt_svc *svc = talloc_get_type(ptr, struct mt_svc);
    time_t now = time(NULL);
    bool process_alive = true;
    int ret;

    ret = service_check_alive(svc);
    switch (ret) {
    case EOK:
        /* all fine */
        break;

    case ECHILD:
        DEBUG(1,("Process (%s) is stopped!\n", svc->name));
        process_alive = false;
        break;

    default:
        /* TODO: should we tear down it ? */
        DEBUG(1,("Checking for service %s(%d) failed!!\n",
                 svc->name, svc->pid));
        break;
    }

    if (process_alive) {
        ret = service_send_ping(svc);
        switch (ret) {
        case EOK:
            /* all fine */
            break;

        case ENXIO:
            DEBUG(1,("Child (%s) not responding! (yet)\n", svc->name));
            break;

        default:
            /* TODO: should we tear it down ? */
            DEBUG(1,("Sending a message to service (%s) failed!!\n", svc->name));
            break;
        }

        if (svc->last_pong != 0) {
            if ((now - svc->last_pong) > (svc->ping_time * 3)) {
                /* too long since we last heard of this process */
                DEBUG(1, ("Killing service [%s], not responding to pings!\n",
                          svc->name));
                monitor_kill_service(svc);
                process_alive = false;
            }
        }

    }

    if (!process_alive) {
        svc_try_restart(svc, now);
        return;
    }

    /* all fine, set up the task checker again */
    set_tasks_checker(svc);
}

static void set_tasks_checker(struct mt_svc *svc)
{
    struct tevent_timer *te = NULL;
    struct timeval tv;

    gettimeofday(&tv, NULL);
    tv.tv_sec += svc->ping_time;
    tv.tv_usec = 0;
    te = tevent_add_timer(svc->mt_ctx->ev, svc, tv, tasks_check_handler, svc);
    if (te == NULL) {
        DEBUG(0, ("failed to add event, monitor offline for [%s]!\n",
                  svc->name));
        /* FIXME: shutdown ? */
    }
    svc->ping_ev = te;
}

static void global_checks_handler(struct tevent_context *ev,
                                  struct tevent_timer *te,
                                  struct timeval t, void *ptr)
{
    struct mt_ctx *ctx = talloc_get_type(ptr, struct mt_ctx);
    struct mt_svc *svc;
    int status;
    pid_t pid;

    errno = 0;
    pid = waitpid(0, &status, WNOHANG);
    if (pid == 0) {
        goto done;
    }

    if (pid == -1) {
        DEBUG(0, ("waitpid returned -1 (errno:%d[%s])\n",
                  errno, strerror(errno)));
        goto done;
    }

    /* let's see if it is a known service, and try to restart it */
    for (svc = ctx->svc_list; svc; svc = svc->next) {
        if (svc->pid == pid) {
            time_t now = time(NULL);
            DEBUG(1, ("Service [%s] did exit\n", svc->name));
            svc_try_restart(svc, now);
            goto done;
        }
    }
    if (svc == NULL) {
        DEBUG(0, ("Unknown child (%d) did exit\n", pid));
    }

done:
    set_global_checker(ctx);
}

static void set_global_checker(struct mt_ctx *ctx)
{
    struct tevent_timer *te = NULL;
    struct timeval tv;

    gettimeofday(&tv, NULL);
    tv.tv_sec += 1; /* once a second */
    tv.tv_usec = 0;
    te = tevent_add_timer(ctx->ev, ctx, tv, global_checks_handler, ctx);
    if (te == NULL) {
        DEBUG(0, ("failed to add global checker event! PANIC TIME!\n"));
        /* FIXME: is this right ? shoulkd we try to clean up first ?*/
        exit(-1);
    }
}

static int monitor_kill_service (struct mt_svc *svc)
{
    int ret;
    ret = kill(svc->pid, SIGTERM);
    if (ret != EOK) {
        DEBUG(0,("Sending signal to child (%s:%d) failed! "
                 "Ignore and pretend child is dead.\n",
                 svc->name, svc->pid));
    }

    return ret;
}

static void shutdown_reply(DBusPendingCall *pending, void *data)
{
    DBusMessage *reply;
    int type;
    struct sbus_conn_ctx *conn_ctx;
    struct mt_svc *svc = talloc_get_type(data, struct mt_svc);

    conn_ctx = svc->mt_conn->conn_ctx;
    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, ("A reply callback was called but no reply was received"
                  " and no timeout occurred\n"));

        /* Destroy this connection */
        monitor_kill_service(svc);
        goto done;
    }

    type = dbus_message_get_type(reply);
    switch(type) {
    case DBUS_MESSAGE_TYPE_METHOD_RETURN:
        /* Ok, we received a confirmation of shutdown */
        break;

    default:
        /* Something went wrong on the client side
         * Time to forcibly kill the service
         */
        DEBUG(0, ("Received an error shutting down service.\n"));
        monitor_kill_service(svc);
    }

    /* No matter what happened here, we need to free the service */
    talloc_free(svc);

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

/* monitor_shutdown_service
 * Orders a monitored service to shut down cleanly
 * This function will free the memory for svc once it
 * completes.
 */
static int monitor_shutdown_service(struct mt_svc *svc)
{
    DBusConnection *conn;
    DBusMessage *msg;
    DBusPendingCall *pending_reply;
    dbus_bool_t dbret;

    /* Stop the service checker */

    conn = sbus_get_connection(svc->mt_conn->conn_ctx);

    /* Construct a shutdown message */
    msg = dbus_message_new_method_call(NULL,
                                       SERVICE_PATH,
                                       SERVICE_INTERFACE,
                                       SERVICE_METHOD_SHUTDOWN);
    if (!msg) {
        DEBUG(0,("Out of memory?!\n"));
        monitor_kill_service(svc);
        talloc_free(svc);
        return ENOMEM;
    }

    dbret = dbus_connection_send_with_reply(conn, msg, &pending_reply,
                                            svc->mt_ctx->service_id_timeout);
    if (!dbret) {
        DEBUG(0, ("D-BUS send failed.\n"));
        dbus_message_unref(msg);
        monitor_kill_service(svc);
        talloc_free(svc);
        return EIO;
    }

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

    return EOK;
}

static void reload_reply(DBusPendingCall *pending, void *data)
{
    DBusMessage *reply;
    struct sbus_conn_ctx *conn_ctx;
    struct mt_svc *svc = talloc_get_type(data, struct mt_svc);

    conn_ctx = svc->mt_conn->conn_ctx;
    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, ("A reply callback was called but no reply was received"
                  " and no timeout occurred\n"));

        /* Destroy this connection */
        sbus_disconnect(conn_ctx);
        goto done;
    }

    /* TODO: Handle cases where the call has timed out or returned
     * with an error.
     */
done:
    dbus_pending_call_unref(pending);
    dbus_message_unref(reply);
}

static int monitor_signal_reconf(struct confdb_ctx *cdb, void *pvt)
{
    struct mt_ctx *ctx = talloc_get_type(pvt, struct mt_ctx);
    DEBUG(1, ("Configuration has changed. Reloading.\n"));
    return update_monitor_config(ctx);
}

static int service_signal_reload(struct mt_svc *svc)
{
    DBusMessage *msg;
    dbus_bool_t dbret;
    DBusConnection *conn;
    DBusPendingCall *pending_reply;

    if (svc->provider && strcasecmp(svc->provider, "local") == 0) {
        /* The local provider requires no signaling */
        return EOK;
    }

    if (!svc->mt_conn) {
        /* Avoid a race condition where we are trying to
         * order a service to reload that hasn't started
         * yet.
         */
        DEBUG(1,("Could not reload service [%s].\n", svc->name));
        return EIO;
    }

    conn = sbus_get_connection(svc->mt_conn->conn_ctx);
    msg = dbus_message_new_method_call(NULL,
                                       SERVICE_PATH,
                                       SERVICE_INTERFACE,
                                       SERVICE_METHOD_RELOAD);
    if (!msg) {
        DEBUG(0,("Out of memory?!\n"));
        monitor_kill_service(svc);
        talloc_free(svc);
        return ENOMEM;
    }

    dbret = dbus_connection_send_with_reply(conn, msg, &pending_reply,
                                            svc->mt_ctx->service_id_timeout);
    if (!dbret) {
        DEBUG(0, ("D-BUS send failed.\n"));
        dbus_message_unref(msg);
        monitor_kill_service(svc);
        talloc_free(svc);
        return EIO;
    }

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

    return EOK;
}

static int check_domain_ranges(struct sss_domain_info *domains)
{
    struct sss_domain_info *dom = domains, *other = NULL;
    uint32_t id_min, id_max;

    while (dom) {
        other = dom->next;
        if (dom->id_max && dom->id_min > dom->id_max) {
            DEBUG(1, ("Domain '%s' does not have a valid ID range\n",
                      dom->name));
            return EINVAL;
        }

        while (other) {
            id_min = MAX(dom->id_min, other->id_min);
            id_max = MIN((dom->id_max ? dom->id_max : UINT32_MAX),
                         (other->id_max ? other->id_max : UINT32_MAX));
            if (id_min <= id_max) {
                DEBUG(1, ("Domains '%s' and '%s' overlap in range %u - %u\n",
                          dom->name, other->name, id_min, id_max));
            }
            other = other->next;
        }
        dom = dom->next;
    }

    return EOK;
}

static int append_data_provider(struct mt_ctx *ctx)
{
    int i;
    char **new_services;

    for (i = 0; ctx->services[i]; i++) {
        if (strcasecmp(ctx->services[i], "dp") == 0) {
            return EOK;
        }
    }

    new_services = talloc_realloc(ctx, ctx->services, char *, i+2);
    if (new_services == NULL) {
        return ENOMEM;
    }
    ctx->services = new_services;

    ctx->services[i] = talloc_asprintf(ctx, "dp");
    if (ctx->services[i] == NULL) {
        return ENOMEM;
    }
    ctx->services[i+1] = NULL;
    DEBUG(4, ("Added mandatory service Data Provider\n"));

    return EOK;
}

int get_monitor_config(struct mt_ctx *ctx)
{
    int ret;

    ret = confdb_get_int(ctx->cdb, ctx,
                         MONITOR_CONF_ENTRY, "sbusTimeout",
                         -1, &ctx->service_id_timeout);
    if (ret != EOK) {
        return ret;
    }

    ctx->service_ctx = talloc_new(ctx);
    if(!ctx->service_ctx) {
        return ENOMEM;
    }
    ret = confdb_get_string_as_list(ctx->cdb, ctx->service_ctx,
                                    SERVICE_CONF_ENTRY, "activeServices",
                                    &ctx->services);
    if (ret != EOK) {
        DEBUG(0, ("No services configured!\n"));
        return EINVAL;
    }
    ret = append_data_provider(ctx);
    if (ret != EOK) {
        DEBUG(0, ("Could not add Data Provider to the list of services!\n"));
        return ret;
    }

    ctx->domain_ctx = talloc_new(ctx);
    if(!ctx->domain_ctx) {
        return ENOMEM;
    }
    ret = confdb_get_domains(ctx->cdb, ctx->domain_ctx, &ctx->domains);
    if (ret != EOK) {
        DEBUG(2, ("No domains configured. LOCAL should always exist!\n"));
        return ret;
    }

    /* Check UID/GID overlaps */
    ret = check_domain_ranges(ctx->domains);
    if (ret != EOK) {
        return ret;
    }

    return EOK;
}

static int get_service_config(struct mt_ctx *ctx, const char *name,
                              struct mt_svc **svc_cfg)
{
    int ret;
    char *path;
    struct mt_svc *svc;

    *svc_cfg = NULL;

    svc = talloc_zero(ctx, struct mt_svc);
    if (!svc) {
        return ENOMEM;
    }
    svc->mt_ctx = ctx;

    svc->name = talloc_strdup(svc, name);
    if (!svc->name) {
        talloc_free(svc);
        return ENOMEM;
    }

    svc->identity = talloc_strdup(svc, name);
    if (!svc->identity) {
        talloc_free(svc);
        return ENOMEM;
    }

    path = talloc_asprintf(svc, "config/services/%s", svc->name);
    if (!path) {
        talloc_free(svc);
        return ENOMEM;
    }

    ret = confdb_get_string(ctx->cdb, svc, path, "command",
                            NULL, &svc->command);
    if (ret != EOK) {
        DEBUG(0,("Failed to start service '%s'\n", svc->name));
        talloc_free(svc);
        return ret;
    }

    if (!svc->command) {
        svc->command = talloc_asprintf(svc, "%s/sssd_%s -d %d",
                                       SSSD_LIBEXEC_PATH, svc->name,
                                       debug_level);
        if (!svc->command) {
            talloc_free(svc);
            return ENOMEM;
        }
    }

    ret = confdb_get_int(ctx->cdb, svc, path, "timeout",
                         MONITOR_DEF_PING_TIME, &svc->ping_time);
    if (ret != EOK) {
        DEBUG(0,("Failed to start service '%s'\n", svc->name));
        talloc_free(svc);
        return ret;
    }

    *svc_cfg = svc;
    talloc_free(path);

    return EOK;
}

static int add_new_service(struct mt_ctx *ctx, const char *name)
{
    int ret;
    struct mt_svc *svc;

    ret = get_service_config(ctx, name, &svc);

    ret = start_service(svc);
    if (ret != EOK) {
        DEBUG(0,("Failed to start service '%s'\n", svc->name));
        talloc_free(svc);
    }

    return ret;
}

static int get_provider_config(struct mt_ctx *ctx, const char *name,
                              struct mt_svc **svc_cfg)
{
    int ret;
    char *path;
    struct mt_svc *svc;

    *svc_cfg = NULL;

    svc = talloc_zero(ctx, struct mt_svc);
    if (!svc) {
        return ENOMEM;
    }
    svc->mt_ctx = ctx;

    svc->name = talloc_strdup(svc, name);
    if (!svc->name) {
        talloc_free(svc);
        return ENOMEM;
    }

    svc->identity = talloc_asprintf(svc, "%%BE_%s", svc->name);
    if (!svc->identity) {
        talloc_free(svc);
        return ENOMEM;
    }

    path = talloc_asprintf(svc, "config/domains/%s", name);
    if (!path) {
        talloc_free(svc);
        return ENOMEM;
    }

    ret = confdb_get_string(ctx->cdb, svc, path,
                            "provider", NULL, &svc->provider);
    if (ret != EOK) {
        DEBUG(0, ("Failed to find provider from [%s] configuration\n", name));
        talloc_free(svc);
        return ret;
    }

    ret = confdb_get_string(ctx->cdb, svc, path,
                            "command", NULL, &svc->command);
    if (ret != EOK) {
        DEBUG(0, ("Failed to find command from [%s] configuration\n", name));
        talloc_free(svc);
        return ret;
    }

    ret = confdb_get_int(ctx->cdb, svc, path, "timeout",
                         MONITOR_DEF_PING_TIME, &svc->ping_time);
    if (ret != EOK) {
        DEBUG(0,("Failed to start service '%s'\n", svc->name));
        talloc_free(svc);
        return ret;
    }

    talloc_free(path);

    /* if no provider is present do not run the domain */
    if (!svc->provider) {
        talloc_free(svc);
        return EIO;
    }

    /* if there are no custom commands, build a default one */
    if (!svc->command) {
        svc->command = talloc_asprintf(svc,
                            "%s/sssd_be -d %d --provider %s --domain %s",
                            SSSD_LIBEXEC_PATH, debug_level,
                            svc->provider, svc->name);
        if (!svc->command) {
            talloc_free(svc);
            return ENOMEM;
        }
    }

    *svc_cfg = svc;
    return EOK;
}

static int add_new_provider(struct mt_ctx *ctx, const char *name)
{
    int ret;
    struct mt_svc *svc;

    ret = get_provider_config(ctx, name, &svc);
    if (ret != EOK) {
        DEBUG(0, ("Could not get provider configuration for [%s]\n",
                  name));
        return ret;
    }

    ret = start_service(svc);
    if (ret != EOK) {
        DEBUG(0,("Failed to start service '%s'\n", svc->name));
        talloc_free(svc);
    }

    return ret;
}

static void remove_service(struct mt_ctx *ctx, const char *name)
{
    int ret;
    struct mt_svc *cur_svc;

    /* Locate the service object in the list */
    cur_svc = ctx->svc_list;
    while (cur_svc != NULL) {
        if (strcasecmp(name, cur_svc->name) == 0)
            break;
        cur_svc = cur_svc->next;
    }
    if (cur_svc != NULL) {
        /* Remove the service from the list */
        DLIST_REMOVE(ctx->svc_list, cur_svc);

        /* Shut it down */
        ret = monitor_shutdown_service(cur_svc);
        if (ret != EOK) {
            DEBUG(0, ("Unable to shut down service [%s]!",
                      name));
            /* TODO: Handle this better */
        }
    }
}

static int update_monitor_config(struct mt_ctx *ctx)
{
    int ret, i, j;
    struct mt_svc *cur_svc;
    struct mt_svc *new_svc;
    struct sss_domain_info *dom, *new_dom;
    struct mt_ctx *new_config;

    new_config = talloc_zero(NULL, struct mt_ctx);
    if(!new_config) {
        return ENOMEM;
    }

    new_config->ev = ctx->ev;
    new_config->cdb = ctx->cdb;
    ret = get_monitor_config(new_config);

    ctx->service_id_timeout = new_config->service_id_timeout;

    /* Compare the old and new active services */
    /* Have any services been shut down? */
    for (i = 0; ctx->services[i]; i++) {
        /* Search for this service in the new config */
        for (j = 0; new_config->services[j]; j++) {
            if (strcasecmp(ctx->services[i], new_config->services[j]) == 0)
                break;
        }
        if (new_config->services[j] == NULL) {
            /* This service is no longer configured.
             * Shut it down.
             */
            remove_service(ctx, ctx->services[i]);
        }
    }

    /* Have any services been added or changed? */
    for (i = 0; new_config->services[i]; i++) {
        /* Search for this service in the old config */
        for (j = 0; ctx->services[j]; j++) {
            if (strcasecmp(new_config->services[i], ctx->services[j]) == 0)
                break;
        }

        if (ctx->services[j] == NULL) {
            /* New service added */
            add_new_service(ctx, new_config->services[i]);
        }
        else {
            /* Service already enabled, check for changes */
            /* Locate the service object in the list */
            cur_svc = ctx->svc_list;
            for (cur_svc = ctx->svc_list; cur_svc; cur_svc = cur_svc->next) {
                if (strcasecmp(ctx->services[i], cur_svc->name) == 0)
                    break;
            }
            if (cur_svc == NULL) {
                DEBUG(0, ("Service entry missing data\n"));
                /* This shouldn't be possible, but if it happens
                 * we'll throw an error
                 */
                talloc_free(new_config);
                return EIO;
            }

            /* Read in the new configuration and compare it with the
             * old one.
             */
            ret = get_service_config(ctx, new_config->services[i], &new_svc);
            if (ret != EOK) {
                DEBUG(0, ("Unable to determine if service has changed.\n"));
                DEBUG(0, ("Disabling service [%s].\n",
                          new_config->services[i]));
                /* Not much we can do here, no way to know whether the
                 * current configuration is safe, and restarting the
                 * service won't work because the new startup requires
                 * this function to work. The only safe thing to do
                 * is stop the service.
                 */
                remove_service(ctx, new_config->services[i]);
                continue;
            }

            if (strcmp(cur_svc->command, new_svc->command) != 0) {
                /* The executable path has changed. We need to
                 * restart the binary completely. If we send a
                 * shutdown command, the monitor will automatically
                 * reload the process with the new command.
                 */
                talloc_free(cur_svc->command);
                talloc_steal(cur_svc, new_svc->command);
                cur_svc->command = new_svc->command;

                /* TODO: be more graceful about this */
                monitor_kill_service(cur_svc);
            }

            cur_svc->ping_time = new_svc->ping_time;

            talloc_free(new_svc);
        }
    }

    /* Replace the old service list with the new one */
    talloc_free(ctx->service_ctx);
    ctx->service_ctx = talloc_steal(ctx, new_config->service_ctx);
    ctx->services = new_config->services;

    /* Compare data providers */
    /* Have any providers been disabled? */
    for (dom = ctx->domains; dom; dom = dom->next) {
        for (new_dom = new_config->domains; new_dom; new_dom = new_dom->next) {
            if (strcasecmp(dom->name, new_dom->name) == 0) break;
        }
        if (new_dom == NULL) {
            /* This provider is no longer configured
             * Shut it down
             */
            remove_service(ctx, dom->name);
        }
    }

    /* Have we added or changed any providers? */
    for (new_dom = new_config->domains; new_dom; new_dom = new_dom->next) {
        /* Search for this service in the old config */
        for (dom = ctx->domains; dom; dom = dom->next) {
            if (strcasecmp(dom->name, new_dom->name) == 0) break;
        }

        if (dom == NULL) {
            /* New provider added */
            add_new_provider(ctx, new_dom->name);
        }
        else {
            /* Provider is already in the list.
             * Check for changes.
             */
            /* Locate the service object in the list */
            cur_svc = ctx->svc_list;
            while (cur_svc != NULL) {
                if (strcasecmp(new_dom->name, cur_svc->name) == 0)
                    break;
                cur_svc = cur_svc->next;
            }
            if (cur_svc == NULL) {
                DEBUG(0, ("Service entry missing data for [%s]\n", new_dom->name));
                /* This shouldn't be possible
                 */
                talloc_free(new_config);
                return EIO;
            }

            /* Read in the new configuration and compare it with
             * the old one.
             */
            ret = get_provider_config(ctx, new_dom->name, &new_svc);
            if (ret != EOK) {
                DEBUG(0, ("Unable to determine if service has changed.\n"));
                DEBUG(0, ("Disabling service [%s].\n",
                          new_config->services[i]));
                /* Not much we can do here, no way to know whether the
                 * current configuration is safe, and restarting the
                 * service won't work because the new startup requires
                 * this function to work. The only safe thing to do
                 * is stop the service.
                 */
                remove_service(ctx, dom->name);
                continue;
            }

            if ((strcmp(cur_svc->command, new_svc->command) != 0) ||
                (strcmp(cur_svc->provider, new_svc->provider) != 0)) {
                /* The executable path or the provider has changed.
                 * We need to restart the binary completely. If we
                 * send a shutdown command, the monitor will
                 * automatically reload the process with the new
                 * command.
                 */
                talloc_free(cur_svc->command);
                talloc_steal(cur_svc, new_svc->command);
                cur_svc->command = new_svc->command;

                /* TODO: be more graceful about this */
                monitor_kill_service(cur_svc);
            }

            cur_svc->ping_time = new_svc->ping_time;
        }

    }

    /* Replace the old domain list with the new one */
    talloc_free(ctx->domain_ctx);
    ctx->domain_ctx = talloc_steal(ctx, new_config->domain_ctx);
    ctx->domains = new_config->domains;

    /* Signal all services to reload their configuration */
    for(cur_svc = ctx->svc_list; cur_svc; cur_svc = cur_svc->next) {
        service_signal_reload(cur_svc);
    }

    talloc_free(new_config);
    return EOK;
}

static void monitor_hup(struct tevent_context *ev,
                        struct tevent_signal *se,
                        int signum,
                        int count,
                        void *siginfo,
                        void *private_data)
{
    struct mt_ctx *ctx = talloc_get_type(private_data, struct mt_ctx);

    DEBUG(1, ("Received SIGHUP. Rereading configuration.\n"));
    update_monitor_config(ctx);
}

static int monitor_cleanup(void)
{
    char *file;
    int ret;
    TALLOC_CTX *tmp_ctx;

    tmp_ctx = talloc_new(NULL);
    if (!tmp_ctx) return ENOMEM;

    file = talloc_asprintf(tmp_ctx, "%s/%s.pid", PID_PATH, "sssd");
    if (file == NULL) {
        return ENOMEM;
    }

    errno = 0;
    ret = unlink(file);
    if (ret == -1) {
        ret = errno;
        DEBUG(0, ("Error removing pidfile! (%d [%s])\n",
                ret, strerror(ret)));
        talloc_free(file);
        return errno;
    }

    talloc_free(file);
    return EOK;
}

static void monitor_quit(struct tevent_context *ev,
                         struct tevent_signal *se,
                         int signum,
                         int count,
                         void *siginfo,
                         void *private_data)
{
    monitor_cleanup();

#if HAVE_GETPGRP
    if (getpgrp() == getpid()) {
        DEBUG(0,("%s: killing children\n", strsignal(signum)));
        kill(-getpgrp(), SIGTERM);
    }
#endif

    exit(0);
}

int read_config_file(const char *config_file)
{
    int ret;
    struct collection_item *sssd_config = NULL;
    struct collection_item *error_list = NULL;

    /* Read the configuration into a collection */
    ret = config_from_file("sssd", config_file, &sssd_config,
                           INI_STOP_ON_ANY, &error_list);
    if (ret != EOK) {
        DEBUG(0, ("Parse error reading configuration file [%s]\n",
                  config_file));
        print_file_parsing_errors(stderr, error_list);
    }

    destroy_collection(error_list);
    destroy_collection(sssd_config);
    return ret;
}

#ifdef HAVE_SYS_INOTIFY_H
static void config_file_changed(struct tevent_context *ev,
                                       struct tevent_fd *fde,
                                       uint16_t flags, void *data)
{
    int ret;
    TALLOC_CTX *tmp_ctx;
    struct inotify_event *in_event;
    char *buf;
    char *name;
    ssize_t len, total_len;
    ssize_t event_size = sizeof(struct inotify_event);
    struct config_file_ctx *file_ctx =
        talloc_get_type(data, struct config_file_ctx);

    DEBUG(1, ("Config file changed\n"));

    tmp_ctx = talloc_new(NULL);
    if (!tmp_ctx) return;

    buf = talloc_size(tmp_ctx, event_size);
    if (!buf) {
        talloc_free(tmp_ctx);
        return;
    }

    total_len = 0;
    while (total_len < event_size) {
        len = read(file_ctx->fd, buf+total_len, event_size-total_len);
        if (len == -1 && errno != EINTR) {
            DEBUG(0, ("Critical error reading inotify file descriptor.\n"));
            talloc_free(tmp_ctx);
            return;
        }
        total_len += len;
    }

    in_event = (struct inotify_event *)buf;

    if (in_event->len > 0) {
        /* Read in the name, even though we don't use it,
         * so that read ptr is in the right place
         */
        name = talloc_size(tmp_ctx, len);
        total_len = 0;
        while (total_len < in_event->len) {
            len = read(file_ctx->fd, &name, in_event->len);
            if (len == -1 && errno != EINTR) {
                DEBUG(0, ("Critical error reading inotify file descriptor.\n"));
                talloc_free(tmp_ctx);
                return;
            }
            total_len += len;
        }
    }

    /* Parse the configuration file */
    ret = confdb_init_db(file_ctx->filename, file_ctx->cdb);
    if (ret != EOK) {
        DEBUG(0, ("Could not reload configuration!"));
        kill(getpid(), SIGTERM);
    }

    /* Tell the monitor to signal the children */
    file_ctx->reconf_fn(file_ctx->cdb, file_ctx->reconf_pvt);

    talloc_free(tmp_ctx);
}
#endif

static void poll_config_file(struct tevent_context *ev,
                                    struct tevent_timer *te,
                                    struct timeval t, void *ptr)
{
    int ret, err;
    struct stat file_stat;
    struct timeval tv;
    struct tevent_timer *timer;
    struct config_file_ctx *file_ctx =
        talloc_get_type(ptr,struct config_file_ctx);

    ret = stat(file_ctx->filename, &file_stat);
    if (ret < 0) {
        err = errno;
        DEBUG(0, ("Could not stat file [%s]. Error [%d:%s]\n",
                  file_ctx->filename, err, strerror(err)));
        /* TODO: If the config file is missing, should we shut down? */
        return;
    }

    if (file_stat.st_mtime != file_ctx->modified) {
        /* Parse the configuration file and signal the children */
        /* Note: this will fire if the modification time changes into the past
         * as well as the future.
         */
        DEBUG(1, ("Config file changed\n"));
        file_ctx->modified = file_stat.st_mtime;

        ret = confdb_init_db(file_ctx->filename, file_ctx->cdb);
        if (ret != EOK) {
            DEBUG(0, ("Could not reload configuration!"));
            kill(getpid(), SIGTERM);
        }

        /* Tell the monitor to signal the children */
        file_ctx->reconf_fn(file_ctx->cdb, file_ctx->reconf_pvt);
    }

    gettimeofday(&tv, NULL);
    tv.tv_sec += CONFIG_FILE_POLL_INTERVAL;
    tv.tv_usec = 0;
    timer = tevent_add_timer(ev, file_ctx->parent_ctx, tv,
                             poll_config_file, file_ctx);
    if (!timer) {
        DEBUG(0, ("Error: Config file no longer monitored for changes!"));
    }
}

static int try_inotify(struct config_file_ctx *file_ctx)
{
#ifdef HAVE_SYS_INOTIFY_H
    int fd, wd, err, fd_args, ret;
    struct tevent_fd *tfd;

    /* Set up inotify to monitor the config file for changes */
    fd = inotify_init();
    if (fd < 0) {
        err = errno;
        DEBUG(0, ("Could not initialize inotify, error [%d:%s]\n",
                  err, strerror(err)));
        return err;
    }

    fd_args = fcntl(fd, F_GETFL, NULL);
    if (fd_args < 0) {
        /* Could not set nonblocking */
        close(fd);
        return EINVAL;
    }

    fd_args |= O_NONBLOCK;
    ret = fcntl(fd, F_SETFL, fd_args);
    if (ret < 0) {
        /* Could not set nonblocking */
        close(fd);
        return EINVAL;
    }

    wd = inotify_add_watch(fd, file_ctx->filename, IN_MODIFY);
    if (wd < 0) {
        err = errno;
        DEBUG(0, ("Could not add inotify watch for file [%s]. Error [%d:%s]\n",
                  file_ctx->filename, err, strerror(err)));
        close(fd);
        return err;
    }

    /* Add the inotify file descriptor to the TEvent context */
    file_ctx->fd = fd;

    tfd = tevent_add_fd(file_ctx->ev, file_ctx, fd, TEVENT_FD_READ,
                        config_file_changed, file_ctx);
    if (!tfd) {
        inotify_rm_watch(fd, wd);
        close(fd);
        return EIO;
    }
    return EOK;
#else
    return EINVAL;
#endif
}

static int monitor_config_file(TALLOC_CTX *mem_ctx,
                        struct confdb_ctx *cdb,
                        struct tevent_context *ev,
                        const char *file,
                        confdb_reconf_fn fn,
                        void *reconf_pvt)
{
    int ret, err;
    struct timeval tv;

    struct stat file_stat;
    struct config_file_ctx *file_ctx;

    struct tevent_timer *timer;

    ret = stat(file, &file_stat);
    if (ret < 0) {
        err = errno;
        DEBUG(0, ("Could not stat file [%s]. Error [%d:%s]\n",
                  file, err, strerror(err)));
        return err;
    }

    file_ctx = talloc_zero(mem_ctx, struct config_file_ctx);
    if (!file_ctx) return ENOMEM;

    file_ctx->parent_ctx = mem_ctx;
    file_ctx->cdb = cdb;
    file_ctx->filename = talloc_strdup(file_ctx, file);
    file_ctx->modified = file_stat.st_mtime;
    file_ctx->reconf_fn = fn;
    file_ctx->reconf_pvt = reconf_pvt;
    file_ctx->ev = ev;

    ret = try_inotify(file_ctx);
    if (ret != EOK) {
        /* Could not monitor file with inotify, fall back to polling */
        gettimeofday(&tv, NULL);
        tv.tv_sec += CONFIG_FILE_POLL_INTERVAL;
        tv.tv_usec = 0;
        timer = tevent_add_timer(ev, mem_ctx, tv, poll_config_file, file_ctx);
        if (!timer) {
            talloc_free(file_ctx);
            return EIO;
        }
    }

    return EOK;
}

int monitor_process_init(TALLOC_CTX *mem_ctx,
                         struct tevent_context *event_ctx,
                         struct confdb_ctx *cdb,
                         const char *config_file)
{
    struct mt_ctx *ctx;
    struct sysdb_ctx *sysdb;
    struct tevent_signal *tes;
    int ret, i;
    char *cdb_file;
    struct sss_domain_info *dom;

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

    /* Initialize the CDB from the configuration file */
    ret = confdb_test(ctx->cdb);
    if (ret == ENOENT) {
        /* First-time setup */

        /* Purge any existing confdb in case an old
         * misconfiguration gets in the way
         */
        talloc_free(ctx->cdb);
        cdb_file = talloc_asprintf(ctx, "%s/%s", DB_PATH, CONFDB_FILE);
        if (cdb_file == NULL) {
            DEBUG(0,("Out of memory, aborting!\n"));
            talloc_free(ctx);
            return ENOMEM;
        }

        unlink(cdb_file);
        ret = confdb_init(ctx, ctx->ev, &ctx->cdb, cdb_file);
        if (ret != EOK) {
            DEBUG(0,("The confdb initialization failed\n"));
            talloc_free(ctx);
            return ret;
        }

        /* Load special entries */
        ret = confdb_create_base(ctx->cdb);
        if (ret != EOK) {
            talloc_free(ctx);
            return ret;
        }
    } else if (ret != EOK) {
        DEBUG(0, ("Fatal error initializing confdb\n"));
        talloc_free(ctx);
        return ret;
    }

    ret = confdb_init_db(config_file, ctx->cdb);
    if (ret != EOK) {
        DEBUG(0, ("ConfDB initialization has failed [%s]\n",
              strerror(ret)));
        talloc_free(ctx);
        return ret;
    }

    /* Read in the monitor's configuration */
    ret = get_monitor_config(ctx);
    if (ret != EOK) {
        talloc_free(ctx);
        return ret;
    }

    /* Watch for changes to the confdb config file */
    ret = monitor_config_file(ctx, cdb, event_ctx, config_file, monitor_signal_reconf, ctx);
    if (ret != EOK) {
        talloc_free(ctx);
        return ret;
    }

    /* Avoid a startup race condition between InfoPipe
     * and NSS. If the sysdb doesn't exist yet, both
     * will try to create it at the same time. So
     * we'll have the monitor create it before either of
     * those processes start.
     */
    ret = sysdb_init(mem_ctx, ctx->ev, ctx->cdb,
                     NULL, &sysdb);
    if (ret != EOK) {
        talloc_free(ctx);
        return ret;
    }
    talloc_free(sysdb);

    /* Initialize D-BUS Server
     * The monitor will act as a D-BUS server for all
     * SSSD processes */
    ret = monitor_dbus_init(ctx);
    if (ret != EOK) {
        talloc_free(ctx);
        return ret;
    }

    /* start all services */
    for (i = 0; ctx->services[i]; i++) {
        add_new_service(ctx, ctx->services[i]);
    }

    /* now start the data providers */
    for (dom = ctx->domains; dom; dom = dom->next) {
        add_new_provider(ctx, dom->name);
    }

    /* now start checking for global events */
    set_global_checker(ctx);

    /* Set up an event handler for a SIGHUP */
    tes = tevent_add_signal(ctx->ev, ctx, SIGHUP, 0,
                            monitor_hup, ctx);
    if (tes == NULL) {
        talloc_free(ctx);
        return EIO;
    }

    /* Set up an event handler for a SIGINT */
    tes = tevent_add_signal(ctx->ev, ctx, SIGINT, 0,
                            monitor_quit, ctx);
    if (tes == NULL) {
        talloc_free(ctx);
        return EIO;
    }

    /* Set up an event handler for a SIGTERM */
    tes = tevent_add_signal(ctx->ev, ctx, SIGTERM, 0,
                            monitor_quit, ctx);
    if (tes == NULL) {
        talloc_free(ctx);
        return EIO;
    }

    return EOK;
}

static int mt_conn_destructor(void *ptr)
{
    struct mt_conn *mt_conn;
    struct mt_svc *svc;

    mt_conn = talloc_get_type(ptr, struct mt_conn);
    svc = mt_conn->svc_ptr;

    /* now clear up so that the rest of the code will know there
     * is no connection attached to the service anymore */
    svc->mt_conn = NULL;

    return 0;
}

/*
 * dbus_service_init
 * This function should initiate a query to the newly connected
 * service to discover the service's identity (invoke the getIdentity
 * method on the new client). The reply callback for this request
 * should set the connection destructor appropriately.
 */
static int dbus_service_init(struct sbus_conn_ctx *conn_ctx, void *data)
{
    struct mt_ctx *ctx;
    struct mt_svc *svc;
    struct mt_conn *mt_conn;
    DBusMessage *msg;
    DBusPendingCall *pending_reply;
    DBusConnection *conn;
    dbus_bool_t dbret;

    DEBUG(3, ("Initializing D-BUS Service\n"));

    ctx = talloc_get_type(data, struct mt_ctx);
    conn = sbus_get_connection(conn_ctx);

    /* hang off this memory to the connection so that when the connection
     * is freed we can call a destructor to clear up the structure and
     * have a way to know we need to restart the service */
    mt_conn = talloc(conn_ctx, struct mt_conn);
    if (!mt_conn) {
        DEBUG(0,("Out of memory?!\n"));
        talloc_free(conn_ctx);
        return ENOMEM;
    }
    mt_conn->conn_ctx = conn_ctx;

    /* at this stage we still do not know what service is this
     * we will know only after we get its identity, so we make
     * up a temporary fake service and complete the operation
     * when we receive the reply */
    svc = talloc_zero(mt_conn, struct mt_svc);
    if (!svc) {
        talloc_free(conn_ctx);
        return ENOMEM;
    }
    svc->mt_ctx = ctx;
    svc->mt_conn = mt_conn;

    mt_conn->svc_ptr = svc;
    talloc_set_destructor((TALLOC_CTX *)mt_conn, mt_conn_destructor);

    /*
     * Set up identity request
     * This should be a well-known path and method
     * for all services
     */
    msg = dbus_message_new_method_call(NULL,
                                       SERVICE_PATH,
                                       SERVICE_INTERFACE,
                                       SERVICE_METHOD_IDENTITY);
    if (msg == NULL) {
        DEBUG(0,("Out of memory?!\n"));
        talloc_free(conn_ctx);
        return ENOMEM;
    }
    dbret = dbus_connection_send_with_reply(conn, msg, &pending_reply,
                                            ctx->service_id_timeout);
    if (!dbret) {
        /*
         * 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);
        talloc_free(conn_ctx);
        return EIO;
    }

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

    return EOK;
}

static void identity_check(DBusPendingCall *pending, void *data)
{
    struct mt_svc *fake_svc;
    struct mt_svc *svc;
    struct sbus_conn_ctx *conn_ctx;
    DBusMessage *reply;
    DBusError dbus_error;
    dbus_uint16_t svc_ver;
    char *svc_name;
    dbus_bool_t ret;
    int type;

    fake_svc = talloc_get_type(data, struct mt_svc);
    conn_ctx = fake_svc->mt_conn->conn_ctx;
    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, ("Serious error. A reply callback was called but no reply was received and no timeout occurred\n"));

        /* Destroy this connection */
        sbus_disconnect(conn_ctx);
        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_STRING, &svc_name,
                                    DBUS_TYPE_UINT16, &svc_ver,
                                    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(conn_ctx);
            goto done;
        }

        DEBUG(4,("Received ID reply: (%s,%d)\n", svc_name, svc_ver));

        /* search this service in the list */
        svc = fake_svc->mt_ctx->svc_list;
        while (svc) {
            ret = strcasecmp(svc->identity, svc_name);
            if (ret == 0) {
                break;
            }
            svc = svc->next;
        }
        if (!svc) {
            DEBUG(0,("Unable to find peer [%s] in list of services, killing connection!\n", svc_name));
            sbus_disconnect(conn_ctx);
            goto done;
        }

        /* transfer all from the fake service and get rid of it */
        fake_svc->mt_conn->svc_ptr = svc;
        svc->mt_conn = fake_svc->mt_conn;
        talloc_free(fake_svc);

        DEBUG(1, ("Service %s connected\n", svc->name));

        /* Set up the destructor for this service */
        break;

    case DBUS_MESSAGE_TYPE_ERROR:
        DEBUG(0,("getIdentity 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(conn_ctx);
        return;
    }

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

/* service_send_ping
 * this function send a dbus ping to a service.
 * It returns EOK if all is fine or ENXIO if the connection is
 * not available (either not yet set up or teared down).
 * Returns e generic error in other cases.
 */
static int service_send_ping(struct mt_svc *svc)
{
    DBusMessage *msg;
    DBusPendingCall *pending_reply;
    DBusConnection *conn;
    dbus_bool_t dbret;

    if (!svc->mt_conn) {
        return ENXIO;
    }

    DEBUG(4,("Pinging %s\n", svc->name));

    conn = sbus_get_connection(svc->mt_conn->conn_ctx);

    /*
     * Set up identity request
     * This should be a well-known path and method
     * for all services
     */
    msg = dbus_message_new_method_call(NULL,
                                       SERVICE_PATH,
                                       SERVICE_INTERFACE,
                                       SERVICE_METHOD_PING);
    if (!msg) {
        DEBUG(0,("Out of memory?!\n"));
        talloc_free(svc->mt_conn->conn_ctx);
        return ENOMEM;
    }

    dbret = dbus_connection_send_with_reply(conn, msg, &pending_reply,
                                            svc->mt_ctx->service_id_timeout);
    if (!dbret) {
        /*
         * Critical Failure
         * We can't communicate on this connection
         * We'll drop it using the default destructor.
         */
        DEBUG(0, ("D-BUS send failed.\n"));
        talloc_free(svc->mt_conn->conn_ctx);
        return EIO;
    }

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

    return EOK;
}

static void ping_check(DBusPendingCall *pending, void *data)
{
    struct mt_svc *svc;
    struct sbus_conn_ctx *conn_ctx;
    DBusMessage *reply;
    const char *dbus_error_name;
    int type;

    svc = talloc_get_type(data, struct mt_svc);
    conn_ctx = svc->mt_conn->conn_ctx;

    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, ("A reply callback was called but no reply was received"
                  " and no timeout occurred\n"));

        /* Destroy this connection */
        sbus_disconnect(conn_ctx);
        goto done;
    }

    type = dbus_message_get_type(reply);
    switch (type) {
    case DBUS_MESSAGE_TYPE_METHOD_RETURN:
        /* ok peer replied,
         * set the reply timestamp into the service structure */

        DEBUG(4,("Service %s replied to ping\n", svc->name));

        svc->last_pong = time(NULL);
        break;

    case DBUS_MESSAGE_TYPE_ERROR:

        dbus_error_name = dbus_message_get_error_name(reply);

        /* timeouts are handled in the main service check function */
        if (strcmp(dbus_error_name, DBUS_ERROR_TIMEOUT) == 0)
            break;

        DEBUG(0,("A service PING returned an error [%s], closing connection.\n",
                 dbus_error_name));
        /* 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(conn_ctx);
    }

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



/* service_check_alive
 * This function checks if the service child is still alive
 */
static int service_check_alive(struct mt_svc *svc)
{
    int status;
    pid_t pid;

    DEBUG(4,("Checking service %s(%d) is still alive\n", svc->name, svc->pid));

    pid = waitpid(svc->pid, &status, WNOHANG);
    if (pid == 0) {
        return EOK;
    }

    if (pid != svc->pid) {
        DEBUG(1, ("bad return (%d) from waitpid() waiting for %d\n",
                  pid, svc->pid));
        /* TODO: what do we do now ? */
        return EINVAL;
    }

    if (WIFEXITED(status)) { /* children exited on it's own */
        /* TODO: check configuration to see if it was removed
         * from the list of process to run */
        DEBUG(0,("Process [%s] exited\n", svc->name));
    }

    return ECHILD;
}

static void free_args(char **args)
{
    int i;

    if (args) {
        for (i = 0; args[i]; i++) free(args[i]);
        free(args);
    }
}


/* parse a string into arguments.
 * arguments are separated by a space
 * '\' is an escape character and can be used only to escape
 * itself or the white space.
 */
static char **parse_args(const char *str)
{
    const char *p;
    char **ret, **r;
    char *tmp;
    int num;
    int i, e;

    tmp = malloc(strlen(str) + 1);
    if (!tmp) return NULL;

    ret = NULL;
    num = 0;
    e = 0;
    i = 0;
    p = str;
    while (*p) {
        switch (*p) {
        case '\\':
            if (e) {
                tmp[i] = '\\';
                i++;
                e = 0;
            } else {
                e = 1;
            }
            break;
        case ' ':
            if (e) {
                tmp[i] = ' ';
                i++;
                e = 0;
            } else {
                tmp[i] = '\0';
                i++;
            }
            break;
        default:
            if (e) {
                tmp[i] = '\\';
                i++;
                e = 0;
            }
            tmp[i] = *p;
            i++;
            break;
        }

        p++;

        /* check if this was the last char */
        if (*p == '\0') {
            if (e) {
                tmp[i] = '\\';
                i++;
                e = 0;
            }
            tmp[i] = '\0';
            i++;
        }
        if (tmp[i-1] != '\0' || strlen(tmp) == 0) {
            /* check next char and skip multiple spaces */
            continue;
        }

        r = realloc(ret, (num + 2) * sizeof(char *));
        if (!r) goto fail;
        ret = r;
        ret[num+1] = NULL;
        ret[num] = strdup(tmp);
        if (!ret[num]) goto fail;
        num++;
        i = 0;
    }

    free(tmp);
    return ret;

fail:
    free(tmp);
    free_args(ret);
    return NULL;
}

static void service_startup_handler(struct tevent_context *ev,
                                    struct tevent_timer *te,
                                    struct timeval t, void *ptr);

static int start_service(struct mt_svc *svc)
{
    struct tevent_timer *te;
    struct timeval tv;

    DEBUG(4,("Queueing service %s for startup\n", svc->name));

    /* Add a timed event to start up the service.
     * We have to do this in order to avoid a race
     * condition where the service being started forks
     * and attempts to connect to the SBUS before
     * the monitor is serving it.
     */
    gettimeofday(&tv, NULL);
    te = tevent_add_timer(svc->mt_ctx->ev, svc, tv,
                         service_startup_handler, svc);
    if (te == NULL) {
        DEBUG(0, ("Unable to queue service %s for startup\n", svc->name));
        return ENOMEM;
    }
    return EOK;
}

static int delist_service(void *ptr) {
    struct mt_svc *svc =
        talloc_get_type(ptr, struct mt_svc);
    DLIST_REMOVE(svc->mt_ctx->svc_list, svc);
    return 0;
}

static void service_startup_handler(struct tevent_context *ev,
                                    struct tevent_timer *te,
                                    struct timeval t, void *ptr)
{
    struct mt_svc *mt_svc;
    char **args;

    mt_svc = talloc_get_type(ptr, struct mt_svc);
    if (mt_svc == NULL) {
        return;
    }

    if (mt_svc->provider && strcasecmp(mt_svc->provider, "local") == 0) {
        /* The LOCAL provider requires no back-end currently
         * We'll add it to the service list, but we don't need
         * to poll it.
         */
        DLIST_ADD(mt_svc->mt_ctx->svc_list, mt_svc);
        talloc_set_destructor((TALLOC_CTX *)mt_svc, delist_service);
        return;
    }

    mt_svc->pid = fork();
    if (mt_svc->pid != 0) {
        if (mt_svc->pid == -1) {
            DEBUG(0, ("Could not fork child to start service [%s]. Continuing.\n", mt_svc->name))
            return;
        }

        /* Parent */
        mt_svc->last_pong = time(NULL);
        DLIST_ADD(mt_svc->mt_ctx->svc_list, mt_svc);
        talloc_set_destructor((TALLOC_CTX *)mt_svc, delist_service);
        set_tasks_checker(mt_svc);

        return;
    }

    /* child */

    args = parse_args(mt_svc->command);
    execvp(args[0], args);

    /* If we are here, exec() has failed
     * Print errno and abort quickly */
    DEBUG(0,("Could not exec %s, reason: %s\n", mt_svc->command, strerror(errno)));

    /* We have to call _exit() instead of exit() here
     * because a bug in D-BUS will cause the server to
     * close its socket at exit() */
    _exit(1);
}

int main(int argc, const char *argv[])
{
    int opt;
    poptContext pc;
    int opt_daemon = 0;
    int opt_interactive = 0;
    char *opt_config_file = NULL;
    char *config_file = NULL;
    int flags = 0;
    struct main_context *main_ctx;
    int ret;

    struct poptOption long_options[] = {
        POPT_AUTOHELP
        SSSD_MAIN_OPTS
        {"daemon", 'D', POPT_ARG_NONE, &opt_daemon, 0, \
         "Become a daemon (default)", NULL }, \
        {"interactive",	'i', POPT_ARG_NONE, &opt_interactive, 0, \
         "Run interactive (not a daemon)", NULL}, \
        {"config", 'c', POPT_ARG_STRING, &opt_config_file, 0, \
         "Specify a non-default config file", NULL}, \
        { 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;
        }
    }

    if (opt_daemon && opt_interactive) {
        fprintf(stderr, "Option -i|--interactive is not allowed together with -D|--daemon\n");
        poptPrintUsage(pc, stderr, 0);
        return 1;
    }

    poptFreeContext(pc);

    if (opt_daemon) flags |= FLAGS_DAEMON;
    if (opt_interactive) flags |= FLAGS_INTERACTIVE;

    if (opt_config_file)
        config_file = talloc_strdup(NULL, opt_config_file);
    else
        config_file = talloc_strdup(NULL, CONFDB_DEFAULT_CONFIG_FILE);
    if(!config_file)
        return 6;

    /* we want a pid file check */
    flags |= FLAGS_PID_FILE;

    /* Parse config file, fail if cannot be done */
    ret = read_config_file(config_file);
    if (ret != EOK) return 4;

    /* set up things like debug , signals, daemonization, etc... */
    ret = server_setup("sssd", flags, MONITOR_CONF_ENTRY, &main_ctx);
    if (ret != EOK) return 2;

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

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

    ret = monitor_cleanup();
    if (ret != EOK) return 5;

    return 0;
}