summaryrefslogtreecommitdiff
path: root/server/alarm-manager.c
blob: 4ce7e5f24f1de5378a78f2be0b7f400dfea29b5e (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
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
/*
 * Copyright (c) 2000 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#include <tzplatform_config.h>
#include <aul.h>
#include <aul_svc.h>
#include <bundle.h>
#include <bundle_internal.h>
#include <vconf.h>
#include <vconf-keys.h>
#include <package-manager.h>
#include <device/display.h>
#include <systemd/sd-login.h>
#include <eventsystem.h>
#include <notification.h>
#include <notification_ipc.h>
#include <notification_internal.h>

#include "alarm.h"
#include "alarm-internal.h"
#include "alarm-manager-db.h"
#include "alarm-manager-util.h"
#include "alarm-manager-dbus.h"

#if !GLIB_CHECK_VERSION(2, 31, 0)
#include <glib/gmacros.h>
#endif

#define BILLION 1000000000 /* for calculating nano seconds */

/* link path for timezone info */
#define TIMEZONE_INFO_LINK_PATH	tzplatform_mkpath(TZ_SYS_ETC, "localtime")

#ifndef RTC_WKALM_BOOT_SET
#define RTC_WKALM_BOOT_SET _IOW('p', 0x80, struct rtc_wkalrm)
#endif

#define _APPFW_FEATURE_WAKEUP_USING_RTC (_get_profile() != PROFILE_TV)


static const char default_rtc[] = "/dev/rtc";
static int gfd = -1;

__alarm_server_context_t alarm_context;

extern bool g_dummy_timer_is_set;

GSList *g_scheduled_alarm_list;
GSList *g_expired_alarm_list;
GSList *g_disabled_alarm_list;
GHashTable *caller_appid_cache_table;

bool is_time_changed = false; /* for calculating next duetime */
static time_t periodic_alarm_standard_time = 0;

struct running_info_t {
	char *appid;
	bool is_running;
};

typedef struct {
	int pid;
	bool is_app;
	char *unique_name;
} appid_cache_t;

static long __get_proper_interval(long interval, int alarm_type);
static void __alarm_add_to_list(__alarm_info_t *__alarm_info);
static void __alarm_generate_alarm_id(__alarm_info_t *__alarm_info, alarm_id_t *alarm_id);
static __alarm_info_t *__alarm_update_in_list(uid_t uid, alarm_id_t alarm_id,
		alarm_info_t *alarm_info, int update_flag, int *error_code);
static bool __alarm_remove_from_list(uid_t uid, alarm_id_t alarm_id,
				     int *error_code);
static void __alarm_set_start_and_end_time(alarm_info_t *alarm_info,
					   __alarm_info_t *__alarm_info);
static void __alarm_update_due_time_of_all_items_in_list(time_t new_time,double diff_time);
static bool __alarm_create(alarm_info_t *alarm_info, alarm_id_t *alarm_id, uid_t uid,
			int pid, periodic_method_e method, long requested_interval, int is_ref,
			char *app_service_name, char *app_service_name_mod,
			const char *dst_service_name, const char *dst_service_name_mod,
			int *error_code);
static bool __alarm_create_appsvc(alarm_info_t *alarm_info, alarm_id_t *alarm_id,
			   long requested_interval, uid_t uid, int pid, char *bundle_data, int *error_code);

static bool __alarm_delete(uid_t uid, alarm_id_t alarm_id, int *error_code);
static bool __alarm_update(uid_t uid, alarm_id_t alarm_id,
			   alarm_info_t *alarm_info, int update_flag, int *error_code);
static void __on_system_time_external_changed(keynode_t *node, void *data);
static void __initialize_alarm_list();
static void __initialize_scheduled_alarm_list();
static void __initialize_noti();
static gboolean __alarm_expired_directly(gpointer user_data);

void _release_alarm_info_t(__alarm_info_t *entry);
static notification_h __get_notification(guchar *data, int datalen);

static bool __get_caller_unique_name(int pid, char *unique_name, int size, bool *is_app, uid_t uid)
{
	char caller_appid[MAX_APP_ID_LEN] = {0,};

	if (unique_name == NULL) {
		LOGE("unique_name should not be NULL.");
		return false;
	}

	if (aul_app_get_appid_bypid_for_uid(pid, caller_appid,
				sizeof(caller_appid), uid) == AUL_R_OK) {
		/* When a caller is an application, the unique name is appID. */
		if (is_app)
			*is_app = true;
		strncpy(unique_name, caller_appid, size - 1);
	} else {
		/* Otherwise, the unique name is /proc/pid/cmdline. */
		char proc_file[MAX_APP_ID_LEN] = {0,};
		char process_name[MAX_APP_ID_LEN] = {0,};
		int fd = 0;
		int i = 0;

		if (is_app)
			*is_app = false;

		snprintf(proc_file, MAX_APP_ID_LEN, "/proc/%d/cmdline", pid);

		fd = open(proc_file, O_RDONLY);
		if (fd < 0) {
			SECURE_LOGE("Caution!! pid(%d) seems to be killed.",
					pid);
			return false;
		} else {
			if (read(fd, process_name, sizeof(process_name) - 1) <= 0) {
				LOGE("Unable to get the process name.");
				close(fd);
				return false;
			}
			close(fd);

			while (process_name[i] != '\0') {
				if (process_name[i] == ' ') {
					process_name[i] = '\0';
					break;
				}
				++i;
			}
			strncpy(unique_name, process_name, size - 1);
		}
	}

	return true;
}

gboolean __hash_table_remove_cb(gpointer key, gpointer value, gpointer user_data)
{
	char *target_name = (char *)user_data;
	appid_cache_t *data = (appid_cache_t *)value;
	if (target_name && data && strcmp(target_name, data->unique_name) == 0) {
		LOGD("Remove cached data of [%s]", target_name);
		return true;
	}

	return false;
}

static bool __get_cached_unique_name(int pid, char *unique_name, int size, bool *is_app, uid_t uid)
{
	appid_cache_t *data;
	bool ret;
	bool _is_app;

	data = (appid_cache_t *)g_hash_table_lookup(caller_appid_cache_table, GINT_TO_POINTER(pid));
	if (data) {
		snprintf(unique_name, MAX_APP_ID_LEN, "%s", data->unique_name);
		if (is_app)
			*is_app = data->is_app;
		LOGD("Get cached unique_name: %s, pid:%d", unique_name, pid);
		return true;
	}

	LOGD("There is no cached unique_name for pid(%d)", pid);

	ret = __get_caller_unique_name(pid, unique_name, size, &_is_app, uid);
	if (ret) {
		g_hash_table_foreach_remove(caller_appid_cache_table, __hash_table_remove_cb, (gpointer)unique_name);
		data = (appid_cache_t *)calloc(1, sizeof(appid_cache_t));
		if (data) {
			data->unique_name = strdup(unique_name);
			data->is_app = _is_app;
			data->pid = pid;
			g_hash_table_insert(caller_appid_cache_table, GINT_TO_POINTER(data->pid), (gpointer)data);
		}

		if (is_app)
			*is_app = _is_app;

		SECURE_LOGD("unique_name= %s", unique_name);
	}

	return ret;
}

void __hashtable_foreach_cb(gpointer key, gpointer value, gpointer user_data)
{
	appid_cache_t *data = (appid_cache_t *)value;
	if (data)
		LOGD("# %s(%d) - %d", data->unique_name, data->pid, data->is_app);
}

void __free_cached_value(gpointer data)
{
	appid_cache_t *value = (appid_cache_t *)data;

	if (value) {
		if (value->unique_name)
			free(value->unique_name);
		free(value);
	}
}

void _rtc_set()
{
	if (_APPFW_FEATURE_WAKEUP_USING_RTC) {
		const char *rtc = default_rtc;
		struct tm due_tm;
		char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
#ifdef _SIMUL /* RTC does not work in simulator. */
		LOGE("because it is simulator's mode, we don't set RTC.");
		return;
#endif

		if (gfd < 0) {
			gfd = open(rtc, O_RDWR);
			if (gfd < 0) {
				LOGE("RTC open failed.");
				return;
			}
		}

		/* Read the RTC time/date */
		int retval = 0;
		char buf[1024];
		char *timebuf = ctime(&alarm_context.c_due_time);
		if (timebuf) {
			timebuf[strlen(timebuf) - 1] = '\0'; /* to avoid new line */
			snprintf(log_message, sizeof(log_message), "wakeup time: %d, %s", (int)alarm_context.c_due_time, timebuf);
		}

		LOGD("alarm_context.c_due_time is %d.", (int)alarm_context.c_due_time);

		if (alarm_context.c_due_time != -1) {
			struct rtc_wkalrm rtc_wkalarm = { 0, };
			rtc_wkalarm.enabled = 0;
			rtc_wkalarm.time.tm_year = 1900;
			rtc_wkalarm.time.tm_mon = 0;
			rtc_wkalarm.time.tm_mday = 1;
			rtc_wkalarm.time.tm_hour = 0;
			rtc_wkalarm.time.tm_min = 0;
			rtc_wkalarm.time.tm_sec = 0;

			retval = ioctl(gfd, RTC_WKALM_SET, &rtc_wkalarm);
			if (retval == -1) {
				if (errno == ENOTTY)
					LOGE("Alarm IRQs is not supported.");

				LOGE("RTC_WKALM_SET disabled ioctl is failed. errno = %s", strerror_r(errno, buf, sizeof(buf)));
				_save_module_log("FAIL: SET RTC", log_message);
				return;
			}
			LOGD("[alarm-server]RTC_WKALM_SET disabled ioctl is successfully done.");

			time_t due_time = alarm_context.c_due_time;
			gmtime_r(&due_time, &due_tm);

			LOGD("Setted RTC Alarm date/time is %d-%d-%d, %02d:%02d:%02d (UTC).",
					due_tm.tm_mday, due_tm.tm_mon + 1, due_tm.tm_year + 1900,
					due_tm.tm_hour, due_tm.tm_min, due_tm.tm_sec);

			rtc_wkalarm.enabled = 1;
			rtc_wkalarm.time.tm_year = due_tm.tm_year;
			rtc_wkalarm.time.tm_mon = due_tm.tm_mon;
			rtc_wkalarm.time.tm_mday = due_tm.tm_mday;
			rtc_wkalarm.time.tm_hour = due_tm.tm_hour;
			rtc_wkalarm.time.tm_min = due_tm.tm_min;
			rtc_wkalarm.time.tm_sec = due_tm.tm_sec;
			retval = ioctl(gfd, RTC_WKALM_SET, &rtc_wkalarm);
			if (retval == -1) {
				if (errno == ENOTTY)
					LOGE("Alarm IRQs is not supported.");

				LOGE("RTC ALARM_SET ioctl is failed. errno = %s", strerror_r(errno, buf, sizeof(buf)));
				_save_module_log("FAIL: SET RTC", log_message);
				return;
			}
			LOGD("[alarm-server]RTC ALARM_SET ioctl is successfully done.");
			_save_module_log("SET RTC", log_message);
		} else {
			LOGE("[alarm-server]alarm_context.c_due_time is"
					"less than 10 sec. RTC alarm does not need to be set");
		}
	} else {
		LOGD("[alarm-server] RTC does not work.");
	}
	return;
}

static bool __set_time(time_t _time)
{
	int ret = 0;
	struct timeval tv;
	struct tm tm, *gmtime_res;

	tv.tv_sec = _time;
	tv.tv_usec = 0;

	gmtime_res = gmtime_r(&(tv.tv_sec), &tm);
	if (!gmtime_res) {
		LOGE("gmtime_r is failed. [%d]", errno);
		return false;
	}

	ret = settimeofday(&tv, NULL);
	if (ret < 0) {
		LOGE("settimeofday is failed.[%d]", errno);
		return false;
	}

	if (_APPFW_FEATURE_WAKEUP_USING_RTC) {
		const char *rtc0 = default_rtc;
		struct rtc_time _rtc_time;
		char buf[1024];
		char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
		char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
		char *timebuf = ctime(&_time);
		if (timebuf) {
			timebuf[strlen(timebuf) - 1] = '\0'; /* to avoid new line */
			snprintf(log_message, sizeof(log_message), "RTC & OS =%ld, %s",
					_time, timebuf);
		}

		if (gfd < 0) {
			gfd = open(rtc0, O_RDWR);
			if (gfd < 0) {
				LOGE("Opening the /dev/rtc is failed.");
				return false;
			}
		}

		memset(&_rtc_time, 0, sizeof(_rtc_time));
		_rtc_time.tm_sec = tm.tm_sec;
		_rtc_time.tm_min = tm.tm_min;
		_rtc_time.tm_hour = tm.tm_hour;
		_rtc_time.tm_mday = tm.tm_mday;
		_rtc_time.tm_mon = tm.tm_mon;
		_rtc_time.tm_year = tm.tm_year;
		_rtc_time.tm_wday = tm.tm_wday;
		_rtc_time.tm_yday = tm.tm_yday;
		_rtc_time.tm_isdst = tm.tm_isdst;

		ret = ioctl(gfd, RTC_SET_TIME, &_rtc_time);
		if (ret == -1) {
			LOGE("ALARM_SET_RTC ioctl is failed. errno = %s", strerror_r(errno, buf, sizeof(buf)));
			strncpy(log_tag, "FAIL: SET RTC", sizeof(log_tag) - 1);
			_save_module_log(log_tag, log_message);
		} else {
			LOGD("ALARM_SET_RTC ioctl is succeed. [%d]", (int)_time);
			strncpy(log_tag, "SET RTC START", sizeof(log_tag) - 1);
			_save_module_log(log_tag, log_message);
			return true;
		}
	} else {
		LOGD("[alarm-server] RTC does not work.");
		return true;
	}

	return false;
}

bool __alarm_clean_list()
{
	__alarm_info_t *entry = NULL;
	GSList *iter = NULL;

	for (iter = alarm_context.alarms; iter != NULL;
			iter = g_slist_next(iter)) {
		entry = (__alarm_info_t *)iter->data;
		_release_alarm_info_t(entry);
	}

	g_slist_free(alarm_context.alarms);
	alarm_context.alarms = NULL;

	return true;
}

static void __alarm_generate_alarm_id(__alarm_info_t *__alarm_info, alarm_id_t *alarm_id)
{
	bool unique_id = false;
	__alarm_info_t *entry = NULL;
	GSList *iter = NULL;

	__alarm_info->alarm_id = g_random_int_range(0, INT_MAX) + 1;
	LOGD("__alarm_info->alarm_id is %d", __alarm_info->alarm_id);

	while (unique_id == false) {
		unique_id = true;

		for (iter = alarm_context.alarms; iter != NULL;
		     iter = g_slist_next(iter)) {
			entry = (__alarm_info_t *)iter->data;
			if (entry->alarm_id == __alarm_info->alarm_id) {
				__alarm_info->alarm_id++;
				unique_id = false;
			}
		}
	}

	*alarm_id = __alarm_info->alarm_id;

	return;
}

static void __alarm_add_to_list(__alarm_info_t *__alarm_info)
{
	alarm_info_t *alarm_info = &__alarm_info->alarm_info;
	__alarm_info_t *entry = NULL;
	GSList *iter = NULL;

	LOGD("[alarm-server]: Before add alarm_id(%d)", __alarm_info->alarm_id);

	alarm_context.alarms = g_slist_append(alarm_context.alarms, __alarm_info);
	LOGD("[alarm-server]: After add alarm_id(%d)", __alarm_info->alarm_id);

	/* alarm list */
	for (iter = alarm_context.alarms; iter != NULL; iter = g_slist_next(iter)) {
		entry = (__alarm_info_t *)iter->data;
		LOGD("[alarm-server]: alarm_id(%d).", entry->alarm_id);
	}

	if (!(alarm_info->alarm_type & ALARM_TYPE_VOLATILE)) {
		if (!_save_alarms(__alarm_info))
			LOGE("Saving alarm_id(%d) in DB is failed.", __alarm_info->alarm_id);
	}
}

static bool __check_bundle_for_update(const gchar *b_data, uid_t uid)
{
	const char *callee_appid;
	bundle *b;
	bool ret = false;

	if (b_data == NULL)
		return true;

	b = bundle_decode((bundle_raw *)b_data, strlen(b_data));
	if (b == NULL)
		return false;

	callee_appid = appsvc_get_appid(b);
	if (callee_appid == NULL) {
		bundle_free(b);
		return false;
	}

	if (_is_ui_app(callee_appid, uid))
		ret = true;

	bundle_free(b);
	return ret;
}

static __alarm_info_t *__alarm_update_in_list(uid_t uid, alarm_id_t alarm_id,
		alarm_info_t *alarm_info, int update_flag, int *error_code)
{
	bool found = false;
	GSList *iter = NULL;
	__alarm_info_t *entry = NULL;
	alarm_info_t *_alarm_info = NULL;
	time_t current_time;

	for (iter = alarm_context.alarms; iter != NULL;
	     iter = g_slist_next(iter)) {
		entry = (__alarm_info_t *)iter->data;
		if (entry->uid == uid &&
				entry->alarm_id == alarm_id) {
			found = true;
			_alarm_info = &entry->alarm_info;

			if (update_flag == ALARM_UPDATE_FLAG_TIME ||
					ALARM_UPDATE_FLAG_WEEK) {
				if (!__check_bundle_for_update(entry->bundle,
						entry->uid)) {
					*error_code = ERR_ALARM_NOT_PERMITTED_APP;
					return NULL;
				}
			}

			if (update_flag == ALARM_UPDATE_FLAG_TIME) {
				__alarm_set_start_and_end_time(alarm_info, entry);
				memcpy(_alarm_info, alarm_info, sizeof(alarm_info_t));

				if (_alarm_info->mode.repeat == ALARM_REPEAT_MODE_ONCE) {
					time(&current_time);
					_alarm_info->reserved_info = current_time;
				}
			} else if (update_flag == ALARM_UPDATE_FLAG_PERIOD) {
				_alarm_info->alarm_type |= ALARM_TYPE_INEXACT;
				_alarm_info->alarm_type |= ALARM_TYPE_PERIOD;
				_alarm_info->mode.repeat = ALARM_REPEAT_MODE_REPEAT;
				_alarm_info->mode.u_interval.interval =
					__get_proper_interval(alarm_info->mode.u_interval.interval,
							_alarm_info->alarm_type);
			} else if (update_flag == ALARM_UPDATE_FLAG_WEEK) {
				_alarm_info->alarm_type &= ~ALARM_TYPE_INEXACT;
				_alarm_info->mode = alarm_info->mode;
			} else if (update_flag == ALARM_UPDATE_FLAG_CLEAR_PERIOD) {
				if (_alarm_info->mode.repeat == ALARM_REPEAT_MODE_REPEAT) {
					_alarm_info->mode.repeat = ALARM_REPEAT_MODE_ONCE;
					_alarm_info->mode.u_interval.interval = 0;
				}
			} else if (update_flag == ALARM_UPDATE_FLAG_CLEAR_WEEK_FLAG) {
				if (_alarm_info->mode.repeat == ALARM_REPEAT_MODE_WEEKLY) {
					_alarm_info->mode.repeat = ALARM_REPEAT_MODE_ONCE;
					_alarm_info->mode.u_interval.interval = 0;
				}
			}
			break;
		}
	}

	if (!found) {
		if (error_code)
			*error_code = ERR_ALARM_INVALID_ID;
		return NULL;
	}

	if (!(alarm_info->alarm_type & ALARM_TYPE_VOLATILE)) {
		if (!_update_alarms(entry))
			LOGE("Updating alarm_id(%d) in DB is failed.", alarm_id);
	}

	return entry;
}

static bool __alarm_remove_from_list(uid_t uid, alarm_id_t alarm_id,
				     int *error_code)
{
	bool found = false;

	alarm_info_t *alarm_info = NULL;

	GSList *iter = NULL;
	__alarm_info_t *entry = NULL;

	/*list alarms */
	LOGD("[alarm-server]: before del : alarm id(%d)", alarm_id);

	for (iter = alarm_context.alarms; iter != NULL; iter = g_slist_next(iter)) {
		entry = (__alarm_info_t *)iter->data;
		if (entry->uid == uid && entry->alarm_id == alarm_id) {
			alarm_info = &entry->alarm_info;

			LOGD("[alarm-server]:Remove alarm id(%d)", entry->alarm_id);

			if (!(alarm_info->alarm_type & ALARM_TYPE_VOLATILE)) {
				if (!_delete_alarms(alarm_id))
					break;
			}

			alarm_context.alarms = g_slist_remove(alarm_context.alarms, iter->data);
			_release_alarm_info_t(entry);
			found = true;
			break;
		}
	}

	LOGD("[alarm-server]: after del\n");

	if (!found) {
		if (error_code)
			*error_code = ERR_ALARM_INVALID_ID;
		return false;
	}

	return true;
}

static void __alarm_set_start_and_end_time(alarm_info_t *alarm_info,
					   __alarm_info_t *__alarm_info)
{
	alarm_date_t *start = &alarm_info->start;
	alarm_date_t *end = &alarm_info->end;

	struct tm alarm_tm = { 0, };

	if (start->year != 0) {
		if ((alarm_info->alarm_type & ALARM_TYPE_RELATIVE) &&  alarm_info->reserved_info != 0) {
			__alarm_info->start = alarm_info->reserved_info;
		} else {
			alarm_tm.tm_year = start->year - 1900;
			alarm_tm.tm_mon = start->month - 1;
			alarm_tm.tm_mday = start->day;

			alarm_tm.tm_hour = start->hour;
			alarm_tm.tm_min = start->min;
			alarm_tm.tm_sec = start->sec;
			alarm_tm.tm_isdst = -1;

			__alarm_info->start = mktime(&alarm_tm);
		}
	} else {
		__alarm_info->start = 0;
	}

	if (end->year != 0) {
		alarm_tm.tm_year = end->year - 1900;
		alarm_tm.tm_mon = end->month - 1;
		alarm_tm.tm_mday = end->day;

		alarm_tm.tm_hour = end->hour;
		alarm_tm.tm_min = end->min;
		alarm_tm.tm_sec = end->sec;

		__alarm_info->end = mktime(&alarm_tm);
	} else {
		__alarm_info->end = 0;
	}
}

static void __alarm_update_due_time_of_all_items_in_list(time_t new_time, double diff_time)
{
	time_t current_time;
	time_t min_time = -1;
	time_t due_time = 0;
	GSList *iter = NULL;
	__alarm_info_t *entry = NULL;
	struct tm *p_time = NULL;
	struct tm due_time_result;
	bool is_rtc_reset = false;
	is_time_changed = true;

	if (periodic_alarm_standard_time != 0)
		periodic_alarm_standard_time += diff_time;

	tzset();
	for (iter = alarm_context.alarms; iter != NULL; iter = g_slist_next(iter)) {
		entry = (__alarm_info_t *)iter->data;
		alarm_info_t *alarm_info = &(entry->alarm_info);
		if (alarm_info->alarm_type & ALARM_TYPE_RELATIVE) {
			/* case of RTC reset */
			if (entry->alarm_info.mode.repeat == ALARM_REPEAT_MODE_ONCE) {
				if ((entry->due_time + diff_time - new_time) >
					(entry->due_time - entry->alarm_info.reserved_info)) {
					LOGE("[ RTC reset]: new time %s %ld, diff %f, id %d duetime %s %ld %ld",
						ctime(&new_time), new_time, diff_time, entry->alarm_id,
						ctime(&entry->due_time), entry->due_time,
						entry->alarm_info.reserved_info);
					continue;
				}

				entry->due_time += diff_time;
				entry->alarm_info.reserved_info = new_time;

			} else {
				entry->due_time += diff_time;
				is_rtc_reset = false;
				if ((entry->due_time - new_time) > alarm_info->mode.u_interval.interval) {
					is_rtc_reset = true;
					entry->due_time = new_time +
						((entry->due_time - new_time) % alarm_info->mode.u_interval.interval);
					LOGE("[ RTC reset]: new time %s %ld, diff %f, id %d duetime %s %ld %ld",
						ctime(&new_time), new_time, diff_time, entry->alarm_id,
						ctime(&entry->due_time), entry->due_time,
						alarm_info->mode.u_interval.interval);
				}
			}

			alarm_date_t *start = &alarm_info->start;	/**< start time of the alarm */
			alarm_date_t *end = &alarm_info->end;	/**< end time of the alarm */

			p_time = localtime_r(&entry->due_time, &due_time_result);
			if (p_time != NULL) {
				start->year = p_time->tm_year + 1900;
				start->month = p_time->tm_mon + 1;
				start->day = p_time->tm_mday;
				start->hour = p_time->tm_hour;
				start->min = p_time->tm_min;
				start->sec = p_time->tm_sec;
			}
			if (entry->start != 0)
				entry->start = entry->due_time;

			if (entry->end != 0 && is_rtc_reset == false) {
				entry->end += diff_time;
				p_time = localtime_r(&entry->end, &due_time_result);
				if (p_time != NULL) {
					end->year = p_time->tm_year + 1900;
					end->month = p_time->tm_mon + 1;
					end->day = p_time->tm_mday;
					end->hour = p_time->tm_hour;
					end->min = p_time->tm_min;
					end->sec = p_time->tm_sec;
				}
			}
		}
		_alarm_set_next_duetime(entry);
	}

	time(&current_time);

	for (iter = alarm_context.alarms; iter != NULL; iter = g_slist_next(iter)) {
		entry = (__alarm_info_t *)iter->data;
		due_time = entry->due_time;

		double interval = 0;

		LOGD("alarm[%d] with duetime(%ld) at current(%ld)", entry->alarm_id, due_time, current_time);
		if (due_time == 0) {	/* 0 means this alarm has been disabled */
			continue;
		}

		interval = difftime(due_time, current_time);

		if (interval < 0) {
			LOGW("The duetime of alarm(%d) is OVER.", entry->alarm_id);

			_alarm_set_next_duetime(entry);
			if (entry->due_time < current_time) {
				const char *dst = entry->callee_pkgid ? entry->callee_pkgid : entry->dst_service_name;
				LOGW("The alarm(%d) is removed [unique_name : %s, dst : %s",
						entry->alarm_id, entry->app_unique_name, dst);

				if (!(entry->alarm_info.alarm_type & ALARM_TYPE_VOLATILE))
					_delete_alarms(entry->alarm_id);

				_save_alarm_info_log("AUTO_DELETE", entry);

				alarm_context.alarms = g_slist_remove(alarm_context.alarms, iter->data);
				_release_alarm_info_t(entry);
				continue;
			} else {
				due_time = entry->due_time;
			}

		}

		interval = difftime(due_time, min_time);

		if ((interval < 0) || min_time == -1)
			min_time = due_time;
	}

	is_time_changed = false;
	alarm_context.c_due_time = min_time;

	g_idle_add(_update_relative_alarms, NULL);
}

static void __set_caller_info(bundle *b, uid_t uid,
		const char *appid, const char *pkgid)
{
	char buf[12];

	snprintf(buf, sizeof(buf), "%u", uid);
	bundle_del(b, AUL_K_ORG_CALLER_UID);
	bundle_add(b, AUL_K_ORG_CALLER_UID, buf);

	bundle_del(b, AUL_K_ORG_CALLER_APPID);
	bundle_add(b, AUL_K_ORG_CALLER_APPID, appid);

	if (pkgid) {
		bundle_del(b, AUL_K_ORG_CALLER_PKGID);
		bundle_add(b, AUL_K_ORG_CALLER_PKGID, pkgid);
	}
}

static bool __alarm_add_and_set(__alarm_info_t *alarm_info, pid_t pid)
{
	time_t current_time;
	struct tm ts_ret;
	char due_time_r[100] = { 0 };

	time(&current_time);

	SECURE_LOGW("[alarm-server]:pid=%d, app_unique_name=%s, \
			app_service_name=%s,dst_service_name=%s, c_due_time=%ld",
			pid, alarm_info->app_unique_name,
			alarm_info->app_service_name,
			alarm_info->dst_service_name,
			alarm_context.c_due_time);

	if (alarm_info->alarm_info.mode.repeat == ALARM_REPEAT_MODE_ONCE)
		alarm_info->alarm_info.reserved_info = current_time;

	if (alarm_context.c_due_time < current_time) {
		LOGW("Caution!! alarm_context.c_due_time (%ld) is less than current time(%ld)",
				alarm_context.c_due_time, current_time);
		alarm_context.c_due_time = -1;
	}

	 _alarm_set_next_duetime(alarm_info);

	if (alarm_info->due_time == 0) {
		LOGW("[alarm-server]:Create a new alarm: due_time is 0. [alarm(%d):repeat_type(%d)]",
				alarm_info->alarm_id, alarm_info->alarm_info.mode.repeat);

		if (alarm_info->alarm_info.mode.repeat == ALARM_REPEAT_MODE_ONCE)
			return false;

		__alarm_add_to_list(alarm_info);
		return true;
	} else if (current_time == alarm_info->due_time) {
		LOGW("[alarm-server]:Create alarm: current_time(%ld) is same as due_time(%ld) [alarm(%d):repeat_type(%d)]",
				current_time, alarm_info->due_time, alarm_info->alarm_id, alarm_info->alarm_info.mode.repeat);

		__alarm_add_to_list(alarm_info);
		_clear_scheduled_alarm_list();
		_add_to_scheduled_alarm_list(alarm_info);
		alarm_context.c_due_time = alarm_info->due_time;

		time_t *_dt = malloc(sizeof(time_t));
		if (_dt) {
			*_dt = alarm_info->due_time;
		} else {
			LOGE("Out of memory");
			return false;
		}

		g_idle_add(__alarm_expired_directly, (gpointer)_dt);

		return true;
	} else if (difftime(alarm_info->due_time, current_time) < 0) {
		LOGW("[alarm-server]: Expired Due Time. \
				[Due time=%ld, Current Time=%ld]!!!Do not add to schedule list. \
				[alarm(%d):repeat_type(%d)]",
				alarm_info->due_time, current_time, alarm_info->alarm_id, alarm_info->alarm_info.mode.repeat);

		if (alarm_info->alarm_info.mode.repeat == ALARM_REPEAT_MODE_ONCE)
			return false;

		__alarm_add_to_list(alarm_info);
		return true;
	} else {
		localtime_r(&(alarm_info->due_time), &ts_ret);
		strftime(due_time_r, 30, "%c", &ts_ret);
		SECURE_LOGD("[alarm-server]:Create a new alarm: alarm(%d) due_time(%s)",
				alarm_info->alarm_id, due_time_r);

		__alarm_add_to_list(alarm_info);
	}

	LOGD("[alarm-server]:alarm_context.c_due_time(%ld), due_time(%ld)",
			alarm_context.c_due_time, alarm_info->due_time);

	if (alarm_context.c_due_time == -1 || alarm_info->due_time < alarm_context.c_due_time) {
		_clear_scheduled_alarm_list();
		_add_to_scheduled_alarm_list(alarm_info);
		_alarm_set_timer(alarm_context.timer, alarm_info->due_time);
		alarm_context.c_due_time = alarm_info->due_time;
		_rtc_set();
	} else if (alarm_info->due_time == alarm_context.c_due_time) {
		_add_to_scheduled_alarm_list(alarm_info);
	}

	return true;
}

static bool __alarm_create_appsvc(alarm_info_t *alarm_info, alarm_id_t *alarm_id,
			   long requested_interval, uid_t uid, int pid, char *bundle_data, int *error_code)
{
	char app_name[MAX_APP_ID_LEN] = { 0 };
	bundle *b;
	const char *callee_appid = NULL;
	bundle_raw *b_data = NULL;
	int datalen = 0;
	bool caller_is_app = false;

	__alarm_info_t *__alarm_info = NULL;

	__alarm_info = (__alarm_info_t *)calloc(1, sizeof(__alarm_info_t));
	if (__alarm_info == NULL) {
		SECURE_LOGE("Caution!! app_pid=%d, calloc failed. it seems to be OOM.", pid);
		*error_code = ERR_ALARM_SYSTEM_FAIL;
		return false;
	}

	__alarm_info->uid = uid;
	__alarm_info->alarm_id = -1;
	__alarm_info->requested_interval = requested_interval;
	__alarm_info->global = false;

	if (__get_cached_unique_name(pid, app_name, sizeof(app_name), &caller_is_app, uid) == false) {
		*error_code = ERR_ALARM_SYSTEM_FAIL;
		_release_alarm_info_t(__alarm_info);
		return false;
	}
	__alarm_info->app_unique_name = strdup(app_name);

	/* caller */
	if (caller_is_app)
		__alarm_info->caller_pkgid = _get_pkgid_by_appid(app_name, uid);

	/* callee */
	b = bundle_decode((bundle_raw *)bundle_data, strlen(bundle_data));
	callee_appid = appsvc_get_appid(b);
	__alarm_info->callee_pkgid = _get_pkgid_by_appid(callee_appid, uid);

	if (b && caller_is_app) {
		__set_caller_info(b, uid, app_name, __alarm_info->caller_pkgid);
		bundle_del(b, AUL_K_REQUEST_TYPE);
		bundle_add(b, AUL_K_REQUEST_TYPE, "indirect-request");
	}

	SECURE_LOGD("caller_pkgid = %s, callee_pkgid = %s",
		__alarm_info->caller_pkgid, __alarm_info->callee_pkgid);

	bundle_encode(b, &b_data, &datalen);
	if (b_data)
		__alarm_info->bundle = strdup((const gchar *)b_data);

	bundle_free(b);
	if (b_data) {
		free(b_data);
		b_data = NULL;
	}

	__alarm_set_start_and_end_time(alarm_info, __alarm_info);
	memcpy(&(__alarm_info->alarm_info), alarm_info, sizeof(alarm_info_t));
	__alarm_generate_alarm_id(__alarm_info, alarm_id);

	if (__alarm_add_and_set(__alarm_info, pid) == false) {
		*error_code = ERR_ALARM_INVALID_TIME;
		_release_alarm_info_t(__alarm_info);
		return false;
	}

	_save_alarm_info_log("CREATE SVC", __alarm_info);

	return true;
}

static bool __alarm_create(alarm_info_t *alarm_info, alarm_id_t *alarm_id, uid_t uid,
			int pid, periodic_method_e method, long requested_interval, int is_ref,
			char *app_service_name, char *app_service_name_mod,
			const char *dst_service_name, const char *dst_service_name_mod,
			int *error_code)
{
	char unique_name[MAX_APP_ID_LEN] = { 0 };
	bool caller_is_app = false;

	__alarm_info_t *__alarm_info = NULL;

	__alarm_info = (__alarm_info_t *)calloc(1, sizeof(__alarm_info_t));
	if (__alarm_info == NULL) {
		SECURE_LOGE("Caution!! app_pid=%d, calloc "
					  "failed. it seems to be OOM\n", pid);
		*error_code = ERR_ALARM_SYSTEM_FAIL;
		return false;
	}
	__alarm_info->uid = uid;
	__alarm_info->alarm_id = -1;
	__alarm_info->method = method;
	__alarm_info->requested_interval = requested_interval;
	__alarm_info->is_ref = is_ref;
	__alarm_info->global = false;

	if (__get_cached_unique_name(pid, unique_name, sizeof(unique_name),
			&caller_is_app, uid) == false) {
		*error_code = ERR_ALARM_SYSTEM_FAIL;
		_release_alarm_info_t(__alarm_info);
		return false;
	}

	/* Get caller_appid to get caller's package id. There is no callee. */
	if (caller_is_app)
		__alarm_info->caller_pkgid = _get_pkgid_by_appid(unique_name, uid);

	SECURE_LOGD("caller_pkgid = %s, callee_pkgid = null", __alarm_info->caller_pkgid);

	__alarm_info->app_unique_name = strdup(unique_name);
	if (app_service_name)
		__alarm_info->app_service_name = strdup(app_service_name);
	if (app_service_name_mod)
		__alarm_info->app_service_name_mod = strdup(app_service_name_mod);
	if (dst_service_name)
		__alarm_info->dst_service_name = strdup(dst_service_name);
	if (dst_service_name_mod)
		__alarm_info->dst_service_name_mod = strdup(dst_service_name_mod);

	__alarm_set_start_and_end_time(alarm_info, __alarm_info);
	memcpy(&(__alarm_info->alarm_info), alarm_info, sizeof(alarm_info_t));
	__alarm_generate_alarm_id(__alarm_info, alarm_id);

	if (__alarm_add_and_set(__alarm_info, pid) == false) {
		*error_code = ERR_ALARM_INVALID_TIME;
		_release_alarm_info_t(__alarm_info);
		return false;
	}

	_save_alarm_info_log("CREATE", __alarm_info);

	return true;
}

static char *__create_new_noti_data(char *noti_data, pid_t pid, uid_t uid)
{
	GVariant *noti_gv;
	guchar *decoded_data;
	int decoded_datalen;
	notification_h noti = NULL;
	char *new_noti_data = NULL;
	guchar* data = NULL;
	int datalen;

	decoded_data = g_base64_decode(noti_data, (gsize *)&decoded_datalen);
	if (decoded_data == NULL)
		return NULL;

	noti = __get_notification(decoded_data, decoded_datalen);
	if (noti == NULL)
		goto end;

	notification_set_indirect_request(noti, pid, uid);

	noti_gv = notification_ipc_make_gvariant_from_noti(noti, false);
	if (noti_gv == NULL)
		goto end;

	datalen = g_variant_get_size(noti_gv);
	if (datalen < 0)
		goto end;

	data = (guchar *)malloc(datalen);
	if (data == NULL)
		goto end;

	g_variant_store(noti_gv, data);
	new_noti_data = g_base64_encode(data, datalen);

end:
	if (data)
		free(data);
	if (noti)
		notification_free(noti);
	if (decoded_data)
		g_free(decoded_data);

	return new_noti_data;
}

static bool __alarm_create_noti(alarm_info_t *alarm_info, alarm_id_t *alarm_id,
			   long requested_interval, uid_t uid, int pid, char *noti_data, int *error_code)
{
	char app_name[MAX_APP_ID_LEN] = { 0 };
	bool caller_is_app = false;
	char *new_noti_data = NULL;

	__alarm_info_t *__alarm_info = NULL;

	__alarm_info = (__alarm_info_t *)calloc(1, sizeof(__alarm_info_t));
	if (__alarm_info == NULL) {
		SECURE_LOGE("Caution!! app_pid=%d, calloc "
					  "failed. it seems to be OOM\n", pid);
		*error_code = ERR_ALARM_SYSTEM_FAIL;
		return false;
	}
	__alarm_info->uid = uid;
	__alarm_info->alarm_id = -1;
	__alarm_info->requested_interval = requested_interval;
	__alarm_info->global = false;

	if (__get_cached_unique_name(pid, app_name, sizeof(app_name), &caller_is_app, uid) == false) {
		*error_code = ERR_ALARM_SYSTEM_FAIL;
		_release_alarm_info_t(__alarm_info);
		return false;
	}
	__alarm_info->app_unique_name = strdup(app_name);

	if (caller_is_app) {
		__alarm_info->caller_pkgid = _get_pkgid_by_appid(app_name, uid);
	}

	SECURE_LOGD("caller_pkgid = %s, callee_pkgid = null",
		__alarm_info->caller_pkgid);

	if (noti_data) {
		if (caller_is_app) {
			new_noti_data = __create_new_noti_data(noti_data, pid,
					uid);
		}

		if (new_noti_data)
			__alarm_info->noti = new_noti_data;
		else
			__alarm_info->noti = strdup(noti_data);
	}

	__alarm_set_start_and_end_time(alarm_info, __alarm_info);
	memcpy(&(__alarm_info->alarm_info), alarm_info, sizeof(alarm_info_t));
	__alarm_generate_alarm_id(__alarm_info, alarm_id);

	if (__alarm_add_and_set(__alarm_info, pid) == false) {
		*error_code = ERR_ALARM_INVALID_TIME;
		_release_alarm_info_t(__alarm_info);
		return false;
	}

	_save_alarm_info_log("CREATE NOTI", __alarm_info);

	return true;
}

static bool __alarm_update(uid_t uid, alarm_id_t alarm_id,
			   alarm_info_t *alarm_info, int update_flag, int *error_code)
{
	time_t current_time;
	char due_time_r[100] = { 0 };
	__alarm_info_t *__alarm_info = NULL;
	bool result = false;
	struct tm ts_ret;

	time(&current_time);

	if (alarm_context.c_due_time < current_time) {
		LOGE("Caution!! alarm_context.c_due_time "
		"(%ld) is less than current time(%ld)", alarm_context.c_due_time, current_time);
		alarm_context.c_due_time = -1;
	}

	__alarm_info = __alarm_update_in_list(uid, alarm_id, alarm_info,
			update_flag, error_code);
	if (!__alarm_info) {
		LOGE("[alarm-server]: requested alarm_id "
		"(%d) does not exist. so this value is invalid id.", alarm_id);
		return false;
	}

	if (__alarm_info->alarm_info.mode.repeat == ALARM_REPEAT_MODE_ONCE)
		__alarm_info->alarm_info.reserved_info = current_time;

	_alarm_set_next_duetime(__alarm_info);

	_save_alarm_info_log("UPDATE", __alarm_info);

	result = _remove_from_scheduled_alarm_list(uid, alarm_id);
	if (result == true && g_slist_length(g_scheduled_alarm_list) == 0) {
		/*there is no scheduled alarm */
		_alarm_disable_timer();
		_alarm_schedule();

		LOGD("[alarm-server]:Update alarm: alarm(%d).", alarm_id);

		_rtc_set();

		if (__alarm_info->due_time == 0)
			LOGE("[alarm-server]:Update alarm: due_time is 0.");

		return true;
	}

	if (__alarm_info->due_time == 0) {
		LOGE("[alarm-server]:Update alarm: "
				"due_time is 0, alarm(%d)\n", alarm_id);
		return true;
	} else if (current_time == __alarm_info->due_time) {
		LOGE("[alarm-server]:Update alarm: "
		"current_time(%ld) is same as due_time(%ld)", current_time,
		__alarm_info->due_time);
		return true;
	} else if (difftime(__alarm_info->due_time, current_time) < 0) {
		LOGE("[alarm-server]: Expired Due Time.[Due time=%ld,\
				Current Time=%ld]!!!Do not add to schedule list\n",
				__alarm_info->due_time, current_time);
		return true;
	} else {
		localtime_r(&(__alarm_info->due_time), &ts_ret);
		strftime(due_time_r, 30, "%c", &ts_ret);
		SECURE_LOGD("[alarm-server]:Update alarm: alarm(%d) "
				    "due_time(%s)\n", alarm_id, due_time_r);
	}

	LOGD("[alarm-server]:alarm_context.c_due_time(%ld), due_time(%ld)",
			alarm_context.c_due_time, __alarm_info->due_time);

	if (alarm_context.c_due_time == -1 || __alarm_info->due_time < alarm_context.c_due_time) {
		_clear_scheduled_alarm_list();
		_add_to_scheduled_alarm_list(__alarm_info);
		_alarm_set_timer(alarm_context.timer, __alarm_info->due_time);
		LOGD("[alarm-server1]:alarm_context.c_due_time "
		     "(%ld), due_time(%ld)", alarm_context.c_due_time, __alarm_info->due_time);
	} else if (__alarm_info->due_time == alarm_context.c_due_time) {
		_add_to_scheduled_alarm_list(__alarm_info);
		LOGD("[alarm-server2]:alarm_context.c_due_time "
		     "(%ld), due_time(%ld)", alarm_context.c_due_time, __alarm_info->due_time);
	}

	_rtc_set();

	return true;
}


static bool __alarm_delete(uid_t uid, alarm_id_t alarm_id, int *error_code)
{
	bool result = false;

	SECURE_LOGD("[alarm-server]:delete alarm: alarm(%d) uid(%d)\n", alarm_id, uid);
	result = _remove_from_scheduled_alarm_list(uid, alarm_id);

	if (!__alarm_remove_from_list(uid, alarm_id, error_code)) {

		SECURE_LOGE("[alarm-server]:delete alarm: "
					  "alarm(%d) uid(%d) has failed with error_code(%d)\n",
					  alarm_id, uid, *error_code);
		return false;
	}

	if (result == true && g_slist_length(g_scheduled_alarm_list) == 0) {
		_alarm_disable_timer();
		_alarm_schedule();
		_rtc_set();
	}

	return true;
}

bool _can_skip_expired_cb(alarm_id_t alarm_id)
{
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	alarm_info_t *alarm = NULL;

	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t *)gs_iter->data;
		if (entry->alarm_id == alarm_id) {
			alarm = &(entry->alarm_info);
			time_t ts = 0;
			struct tm ts_tm;
			int dur = entry->requested_interval;
			int from, to;

			if (dur == 0 || !(alarm->alarm_type & ALARM_TYPE_PERIOD) || entry->method == CUT_OFF)
				return false;

			ts_tm.tm_hour = alarm->start.hour;
			ts_tm.tm_min = alarm->start.min;
			ts_tm.tm_sec = alarm->start.sec;

			ts_tm.tm_year = alarm->start.year - 1900;
			ts_tm.tm_mon = alarm->start.month - 1;
			ts_tm.tm_mday = alarm->start.day;
			ts_tm.tm_isdst = -1;

			ts = mktime(&ts_tm);

			from = (ts / dur) * dur;
			to = from + dur;

			if (ts >= from && ts < to && from > ts - alarm->mode.u_interval.interval)
				return false;

			return true;
		}
	}

	return false;
}

static int __find_login_user(uid_t *uid)
{
	uid_t *uids;
	int ret, i;
	char *state;

	ret = sd_get_uids(&uids);
	if (ret <= 0)
		return -1;

	for (i = 0; i < ret; i++) {
		if (sd_uid_get_state(uids[i], &state) < 0) {
			free(uids);
			return -1;
		} else {
			if (!strncmp(state, "online", 6)) {
				*uid = uids[i];
				free(uids);
				free(state);
				return 0;
			}
		}
	}

	free(uids);
	free(state);
	return -1;
}

static notification_h __get_notification(guchar *data, int datalen)
{
	int ret;
	GVariant *noti_gv = NULL;
	GVariant *body = NULL;
	notification_h noti;

	if (data == NULL || datalen <= 0)
		return NULL;

	noti_gv = g_variant_new_from_data(G_VARIANT_TYPE("(v)"),
			data, datalen, TRUE, NULL, NULL);

	if (noti_gv == NULL)
		return NULL;

	g_variant_get(noti_gv, "(v)", &body);

	if (body == NULL) {
		g_variant_unref(noti_gv);
		return NULL;
	}

	noti = notification_create(NOTIFICATION_TYPE_NOTI);
	if (noti == NULL) {
		g_variant_unref(body);
		g_variant_unref(noti_gv);
		return NULL;
	}

	ret = notification_ipc_make_noti_from_gvariant(noti, body);

	if (ret != NOTIFICATION_ERROR_NONE) {
		g_variant_unref(body);
		g_variant_unref(noti_gv);
		notification_free(noti);
		return NULL;
	}

	g_variant_unref(body);
	g_variant_unref(noti_gv);

	return noti;
}

static void __expire_notification(__alarm_info_t *alarm_info)
{
	int ret;
	int datalen;
	notification_h noti;
	guchar *noti_data;
	int expire_mode = ALARM_EXPIRE_MODE_NORMAL;

	noti_data = g_base64_decode(alarm_info->noti,
			(gsize *)&datalen);
	if (!noti_data) {
		LOGE("Failed to decode noti data");
		return;
	}

	noti = __get_notification(noti_data, datalen);
	if (noti == NULL) {
		LOGE("Failed to get notification");
		g_free(noti_data);
		return;
	}

	if (vconf_get_int(VCONFKEY_ALARM_EXPIRE_MODE, &expire_mode) != 0)
		LOGE("Failed to get value of VCONFKEY_ALARM_EXPIRE_MODE");

	LOGD("Value of alarm_expire_mode [%d]", expire_mode);

	if (expire_mode == ALARM_EXPIRE_MODE_NORMAL)
		device_display_change_state(DISPLAY_STATE_NORMAL);

	ret = notification_post_for_uid(noti, alarm_info->uid);
	if (ret != NOTIFICATION_ERROR_NONE)
		LOGE("Failed to post notification");

	notification_free(noti);
	g_free(noti_data);
}

static void __expire_app_control(__alarm_info_t *alarm_info)
{
	char alarm_id_val[32];
	bundle *b = NULL;
	char *appid = NULL;
	int b_len = 0;
	int app_pid = 0;
	int ret;
	int result = 0;
	int expire_mode = ALARM_EXPIRE_MODE_NORMAL;
	uid_t target_uid;

	b_len = strlen(alarm_info->bundle);
	b = bundle_decode((bundle_raw *)(alarm_info->bundle), b_len);
	if (b == NULL) {
		LOGE("Error!!!..Unable to decode the bundle!!\n");
		return;
	}

	snprintf(alarm_id_val, sizeof(alarm_id_val), "%d", alarm_info->alarm_id);

	if (bundle_add_str(b, "http://tizen.org/appcontrol/data/alarm_id", alarm_id_val)) {
		LOGE("Unable to add alarm id to the bundle\n");
		bundle_free(b);
		return;
	}

	app_pid = _get_pid_from_appid(alarm_info->app_unique_name,
			alarm_info->uid);
	SECURE_LOGW("alarm_expired : from [uid : %d, pid : %d, pkgid : %s, "
			"unique_name : %s]", alarm_info->uid, app_pid,
			alarm_info->caller_pkgid, alarm_info->app_unique_name);

	if (_compare_api_version(&result, app_pid, alarm_info->uid) < 0) {
		LOGE("Unable to check api version\n");
		result = -1;
	}

	if (result < 0) {
		/* before 2.4 */
		if (aul_svc_run_service_async_for_uid(b, 0, NULL, NULL, alarm_info->uid) < 0)
			LOGE("Unable to run app svc\n");
		else
			LOGD("Successfuly run app svc\n");
	} else {
		/* since 2.4 */
		appid = (char *)appsvc_get_appid(b);
		if ((alarm_info->alarm_info.alarm_type & ALARM_TYPE_NOLAUNCH) && !aul_app_is_running(appid)) {
			LOGE("This alarm is ignored\n");
		} else if (!(alarm_info->alarm_info.alarm_type & ALARM_TYPE_INEXACT) ||
				!_can_skip_expired_cb(alarm_info->alarm_id)) {
			if (alarm_info->global) {
				if (__find_login_user(&target_uid) < 0) {
					LOGE("Fail to get login user\n");
					ret = -1;
				} else {
					ret = aul_svc_run_service_async_for_uid(b, 0, NULL, NULL, target_uid);
				}
			} else {
				ret = aul_svc_run_service_async_for_uid(b, 0, NULL, NULL, alarm_info->uid);
			}

			if (ret < 0) {
				LOGE("Unable to launch app [%s] \n", appid);
			} else {
				if (vconf_get_int(VCONFKEY_ALARM_EXPIRE_MODE, &expire_mode) != 0)
					LOGE("Failed to get value of VCONFKEY_ALARM_EXPIRE_MODE");

				LOGD("Successfuly ran app svc (expire_mode : %d)", expire_mode);

				if (_is_ui_app(appid, alarm_info->uid) &&
						expire_mode == ALARM_EXPIRE_MODE_NORMAL)
					device_display_change_state(DISPLAY_STATE_NORMAL);
			}
		}
	}

	bundle_free(b);
}

static int __app_info_iter(const aul_app_info *info, void *data)
{
	struct running_info_t *app_info = (struct running_info_t *)data;

	if (strcmp(app_info->appid, info->appid) == 0)
		app_info->is_running = true;

	return 0;
}

static void __expire_dbus_activation(__alarm_info_t *alarm_info)
{
	const char *destination_app_service_name = NULL;
	char appid[MAX_SERVICE_NAME_LEN] = { 0, };
	struct running_info_t app_info;
	bundle *kb;
	uid_t target_uid;
	bool is_app = false;

	if (alarm_info->dst_service_name == NULL) {
		SECURE_LOGD("[alarm-server]:destination is null, so we send expired alarm to %s.",
				alarm_info->app_service_name);
		destination_app_service_name = alarm_info->app_service_name_mod;
	} else {
		SECURE_LOGD("[alarm-server]:destination :%s",
				alarm_info->dst_service_name);
		destination_app_service_name = alarm_info->dst_service_name_mod;
	}

	/*
	 * we should consider a situation that
	 * destination_app_service_name is owner_name like (:xxxx) and
	 * application's pid which registered this alarm was killed.In that case,
	 * we don't need to send the expire event because the process was killed.
	 * this causes needless message to be sent.
	 */

	if (alarm_info->dst_service_name == NULL) {
		if (alarm_info->app_service_name != NULL && strlen(alarm_info->app_service_name) > 6)
			strncpy(appid, alarm_info->app_service_name + 6, sizeof(appid) - 1);
	} else {
		if (strlen(alarm_info->dst_service_name) > 6)
			strncpy(appid,	alarm_info->dst_service_name + 6, sizeof(appid) - 1);
	}

	if (alarm_info->uid >= REGULAR_UID_MIN) {
		is_app = _is_app(appid, alarm_info->uid);
	}
	LOGD("appid : %s app?(%d)", appid, is_app);

	/* Case #3-1. The process was killed && App type
	 * This app is launched and owner of DBus connection is changed. and then, expiration noti is sent by DBus. */
	app_info.is_running = false;
	if (is_app) {
		app_info.appid = appid;
		aul_app_get_all_running_app_info_for_uid(__app_info_iter,
				&app_info, alarm_info->uid);

		SECURE_LOGD("[alarm-server]: destination_app_id :%s", appid);
	}

	if (is_app && !app_info.is_running) {
		__expired_alarm_t *expire_info;
		char alarm_id_str[32] = { 0, };

		if (alarm_info->alarm_info.alarm_type & ALARM_TYPE_WITHCB) {
			__alarm_remove_from_list(alarm_info->uid, alarm_info->alarm_id, NULL);
			LOGW("[alarm-server]:This alarm_type is WITHCB");
			return;
		}

		expire_info = (__expired_alarm_t *)malloc(sizeof(__expired_alarm_t));
		if (G_UNLIKELY(NULL == expire_info)) {
			LOGE("[alarm-server]:Malloc failed!Can't notify alarm expiry info\n");
			return;
		}
		memset(expire_info, '\0', sizeof(__expired_alarm_t));
		strncpy(expire_info->service_name, destination_app_service_name, MAX_SERVICE_NAME_LEN-1);
		expire_info->alarm_id = alarm_info->alarm_id;
		expire_info->uid = alarm_info->uid;
		g_expired_alarm_list = g_slist_append(g_expired_alarm_list, expire_info);

		snprintf(alarm_id_str, 31, "%d", alarm_info->alarm_id);

		SECURE_LOGD("before aul_launch appid(%s) alarm_id_str(%s)", appid, alarm_id_str);

		kb = bundle_create();
		bundle_add_str(kb, "__ALARM_MGR_ID", alarm_id_str);

		if (alarm_info->global) {
			if (__find_login_user(&target_uid) < 0)
				LOGE("Fail to get login user\n");
			else
				aul_launch_app_for_uid(appid, kb, target_uid); /* on_bus_name_owner_changed will be called. */
		} else {
			aul_launch_app_for_uid(appid, kb, alarm_info->uid); /* on_bus_name_owner_changed will be called. */
		}

		bundle_free(kb);
	} else {
		/* Case #3-2. The process is alive or was killed && non-app type(daemon)
		 * Expiration noti is sent by DBus. it makes the process alive. (dbus auto activation) */
		LOGD("before alarm_send_noti_to_application");

		_alarm_send_noti_to_application_by_dbus(destination_app_service_name,
				alarm_info->alarm_id, alarm_info->alarm_info.msec, alarm_info->uid); /* dbus auto activation */
		LOGD("after _alarm_send_noti_to_application_by_dbus");
	}

	return 0;
}

void _alarm_expired()
{
	__alarm_info_t *__alarm_info = NULL;
	GSList *iter = NULL;
	__scheduled_alarm_t *alarm = NULL;

	LOGD("[alarm-server]: Enter");

	time_t current_time;
	double interval;

	time(&current_time);

	interval = difftime(alarm_context.c_due_time, current_time);
	LOGD("[alarm-server]: c_due_time(%ld), current_time(%ld), interval(%f)",
		alarm_context.c_due_time, current_time, interval);

	if (alarm_context.c_due_time > current_time + 1) {
		LOGE("[alarm-server]: False Alarm. due time is (%ld) seconds future",
			alarm_context.c_due_time - current_time);
		goto done;
	}
	/* 10 seconds is maximum permitted delay from timer expire to this function */
	if (alarm_context.c_due_time + 10 < current_time) {
		LOGE("[alarm-server]: False Alarm. due time is (%ld) seconds past.",
			current_time - alarm_context.c_due_time);
		goto done;
	}

	for (iter = g_scheduled_alarm_list; iter != NULL; iter = g_slist_next(iter)) {
		alarm = (__scheduled_alarm_t *)iter->data;
		__alarm_info = alarm->__alarm_info;

		/* Case #1. The process is an application launched by app_control.
		 * It registered an alarm using launch-based APIs like alarm_schedule_xxx, alarmmgr_xxx_appsvc. */
		if (__alarm_info->bundle != NULL) {
			__expire_app_control(__alarm_info);
		} else if (__alarm_info->noti != NULL) {
		/* Case #2. The process is an application launched by notification. */
			__expire_notification(__alarm_info);
		} else {
		/* Case #3. Expiration noti is sent by DBus.
		 * 3-1. The process was killed && App type
		 * 3-2. The process is alive or was killed && non-app type(daemon) */
			__expire_dbus_activation(__alarm_info);
		}

		LOGD("alarm_id[%d] is expired.", __alarm_info->alarm_id);

		_save_alarm_info_log("EXPIRED", __alarm_info);

		if (__alarm_info->alarm_info.mode.repeat == ALARM_REPEAT_MODE_ONCE) {
			__alarm_remove_from_list(__alarm_info->uid, __alarm_info->alarm_id, NULL);
		} else {
			_alarm_set_next_duetime(__alarm_info);
			_save_alarm_info_log("DUETIME", __alarm_info);
		}
	}

done:
	_clear_scheduled_alarm_list();
	alarm_context.c_due_time = -1;

	LOGD("[alarm-server]: Leave");
}


static void __on_system_time_external_changed(keynode_t *node, void *data)
{
	double diff_time = 0.0;
	time_t cur_time = 0;

	_alarm_disable_timer();

	if (node) {
		diff_time = vconf_keynode_get_dbl(node);
	} else {
		if (vconf_get_dbl(VCONFKEY_SYSTEM_TIMECHANGE_EXTERNAL, &diff_time) != 0) {
			LOGE("Failed to get value of VCONFKEY_SYSTEM_TIMECHANGE_EXTERNAL.");
			return;
		}
	}

	tzset();
	time(&cur_time);

	LOGD("diff_time is %f, New time is %s\n", diff_time, ctime(&cur_time));

	LOGD("[alarm-server] System time has been changed externally\n");
	LOGD("1.alarm_context.c_due_time is %ld\n",
			    alarm_context.c_due_time);

	if (!__set_time(cur_time)) { /* Change both OS time and RTC */
		LOGE("Failed to change both OS time and RTC");
		_clear_scheduled_alarm_list();
		_alarm_schedule();
		_rtc_set();
		return;
	}

	vconf_set_int(VCONFKEY_SYSTEM_TIME_CHANGED, (int)diff_time);
	bundle *b = NULL;
	b = bundle_create();
	bundle_add_str(b, EVT_KEY_TIME_CHANGED, EVT_VAL_TIME_CHANGED_TRUE);
	eventsystem_send_system_event(SYS_EVENT_TIME_CHANGED, b);
	bundle_free(b);

	__alarm_update_due_time_of_all_items_in_list(cur_time, diff_time);

	LOGD("2.alarm_context.c_due_time is %ld\n",
			    alarm_context.c_due_time);
	_clear_scheduled_alarm_list();
	_alarm_schedule();
	_rtc_set();

	_save_module_log("SET RTC END", "requested by vconf");

	return;
}

static int __on_app_enable_cb(uid_t target_uid, int req_id,
		const char *pkg_type, const char *pkgid, const char *appid,
		const char *key, const char *val, const void *pmsg, void *data)
{
	SECURE_LOGD("appid:%s, key:%s, val:%s, req_id: %d", appid, key, val, req_id);

	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	bool is_restored = false;

	if (key && strncmp(key, "end", 3) == 0 && val && strncmp(val, "ok", 2) == 0) {
		SECURE_LOGD("Enable appid(%s)", appid);
		for (gs_iter = g_disabled_alarm_list; gs_iter != NULL; ) {
			entry = (__alarm_info_t *)gs_iter->data;

			gs_iter = g_slist_next(gs_iter);
			if (strncmp(appid, entry->app_unique_name, strlen(appid)) == 0) {
				_alarm_set_next_duetime(entry);
				SECURE_LOGD("Restore alarm_id(%d) duetime(%d) appid(%s)",
						entry->alarm_id, (int)(entry->due_time), appid);
				alarm_context.alarms = g_slist_append(alarm_context.alarms, entry);
				g_disabled_alarm_list = g_slist_remove(g_disabled_alarm_list, entry);

				if (!(entry->alarm_info.alarm_type & ALARM_TYPE_VOLATILE))
					_update_db_for_disabled_alarm(entry->alarm_id, false);
				is_restored = true;
			}
		}

		if (is_restored) {
			_alarm_disable_timer();
			_clear_scheduled_alarm_list();
			_alarm_schedule();
			_rtc_set();
		}
	}

	return 0;
}

static int __on_app_disable_cb(uid_t target_uid, int req_id,
		const char *pkg_type, const char *pkgid, const char *appid,
		const char *key, const char *val, const void *pmsg, void *data)
{
	SECURE_LOGD("appid:%s, key:%s, val:%s, req_id: %d", appid, key, val, req_id);

	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	bool is_disabled = false;

	if (key && strncmp(key, "end", 3) == 0 && val && strncmp(val, "ok", 2) == 0) {
		SECURE_LOGD("Disable appid(%s)", appid);
		for (gs_iter = alarm_context.alarms; gs_iter != NULL; ) {
			entry = (__alarm_info_t *)gs_iter->data;

			gs_iter = g_slist_next(gs_iter);
			if (strncmp(appid, entry->app_unique_name, strlen(appid)) == 0) {
				if (!(entry->alarm_info.alarm_type & ALARM_TYPE_VOLATILE))
					_update_db_for_disabled_alarm(entry->alarm_id, true);
				g_disabled_alarm_list = g_slist_append(g_disabled_alarm_list, entry);
				alarm_context.alarms = g_slist_remove(alarm_context.alarms, entry);
				is_disabled = true;
			}
		}

		if (is_disabled) {
			_alarm_disable_timer(alarm_context);
			_clear_scheduled_alarm_list();
			_alarm_schedule();
			_rtc_set();
		}
	}

	return 0;
}

static int __on_app_uninstalled(uid_t target_uid, int req_id, const char *pkg_type,
				const char *pkgid, const char *key, const char *val,
				const void *pmsg, void *user_data)
{
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	alarm_info_t *alarm_info = NULL;
	bool is_deleted = false;

	SECURE_LOGD("pkg_type(%s), pkgid(%s), key(%s), value(%s)", pkg_type, pkgid, key, val);

	if (strncmp(key, "end", 3) == 0 && strncmp(val, "ok", 2) == 0) {
		for (gs_iter = alarm_context.alarms; gs_iter != NULL;) {
			entry = (__alarm_info_t *)gs_iter->data;

			const char *caller_pkgid = entry->caller_pkgid;
			const char *callee_pkgid = entry->callee_pkgid;
			int pid = _get_pid_from_appid(entry->app_unique_name, entry->uid);

			gs_iter = g_slist_next(gs_iter);
			if ((caller_pkgid && strncmp(pkgid, caller_pkgid, strlen(pkgid)) == 0) ||
					(callee_pkgid && strncmp(pkgid, callee_pkgid, strlen(pkgid)) == 0)) {
				if (_remove_from_scheduled_alarm_list(entry->uid, entry->alarm_id))
					is_deleted = true;

				alarm_info = &entry->alarm_info;
				if (!(alarm_info->alarm_type & ALARM_TYPE_VOLATILE)) {
					if (!_delete_alarms(entry->alarm_id))
						SECURE_LOGE("_delete_alarms() is failed. pkgid[%s], alarm_id[%d]", pkgid, entry->alarm_id);
				}

				if (g_hash_table_remove(caller_appid_cache_table, GINT_TO_POINTER(pid)) == true)
					LOGD("Remove cachd data of pid[%d]", pid);

				SECURE_LOGD("Remove pkgid[%s], alarm_id[%d]", pkgid, entry->alarm_id);
				alarm_context.alarms = g_slist_remove(alarm_context.alarms, entry);
				_release_alarm_info_t(entry);

			}
		}

		if (is_deleted && (g_slist_length(g_scheduled_alarm_list) == 0)) {
			_alarm_disable_timer();
			_alarm_schedule();
			_rtc_set();
		}
	}

	return ALARMMGR_RESULT_SUCCESS;
}

static long __get_proper_interval(long interval, int alarm_type)
{
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	long maxInterval = 60;

	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t *)gs_iter->data;
		if (entry->alarm_info.alarm_type & ALARM_TYPE_PERIOD) {
			if (entry->alarm_info.mode.u_interval.interval <= interval &&
					entry->alarm_info.mode.u_interval.interval > maxInterval)
				maxInterval = entry->alarm_info.mode.u_interval.interval;
		}
	}

	while ((maxInterval * 2 <= interval && maxInterval < LONG_MAX / 2) ||
			(alarm_type & ALARM_TYPE_INEXACT && maxInterval < MIN_INEXACT_INTERVAL))
		maxInterval *= 2;

	return maxInterval;
}

static gboolean __alarm_expired_directly(gpointer user_data)
{
	if (g_scheduled_alarm_list == NULL || g_scheduled_alarm_list->data == NULL)
		return false;

	time_t *time_sec = (time_t *)user_data;
	__scheduled_alarm_t *alarm = (__scheduled_alarm_t *)g_scheduled_alarm_list->data;
	__alarm_info_t *alarm_info = alarm->__alarm_info;

	/* Expire alarms with duetime equal to newtime by force */
	if (alarm_info->due_time == *time_sec) {
		_display_lock_state(DEVICED_LCD_OFF, DEVICED_STAY_CUR_STATE, 0);

		if (g_dummy_timer_is_set == true) {
			LOGD("dummy alarm timer has expired.");
		} else {
			LOGD("due_time=%ld is expired.", alarm_info->due_time);
			_alarm_expired();
		}

		_alarm_schedule();
		_rtc_set();

		_display_unlock_state(DEVICED_LCD_OFF, DEVICED_SLEEP_MARGIN);
	}

	if (time_sec)
		free(time_sec);

	return false;
}

void __reschedule_alarms_with_newtime(time_t cur_time, time_t new_time, double diff_time)
{
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};

	time_t *_new_time;
	vconf_set_int(VCONFKEY_SYSTEM_TIME_CHANGED, (int)diff_time);
	bundle *b = NULL;
	b = bundle_create();
	bundle_add_str(b, EVT_KEY_TIME_CHANGED, EVT_VAL_TIME_CHANGED_TRUE);
	eventsystem_send_system_event(SYS_EVENT_TIME_CHANGED, b);
	bundle_free(b);

	__alarm_update_due_time_of_all_items_in_list(new_time, diff_time); /* Rescheduling alarms with ALARM_TYPE_RELATIVE */
	LOGD("Next duetime is %ld", alarm_context.c_due_time);

	_clear_scheduled_alarm_list();
	_alarm_schedule();
	_rtc_set();

	char *timebuf = ctime((const time_t *)&new_time);
	if (timebuf) {
		timebuf[strlen(timebuf) - 1] = '\0'; /* to avoid newline */
		snprintf(log_message, sizeof(log_message), "Current: %ld, New: %ld, %s, diff: %f", cur_time, new_time, timebuf, diff_time);
	}

	_save_module_log("CHANGE TIME", log_message);

	_new_time = malloc(sizeof(time_t));
	if (_new_time) {
		*_new_time = new_time;
	} else {
		LOGE("Out of memory");
		return;
	}

	g_idle_add(__alarm_expired_directly, (gpointer)_new_time); /* Expire alarms with duetime equal to newtime directly */
	return;
}

static int __check_modifiable(uid_t uid, pid_t pid, int alarm_id)
{
	bool caller_is_app = false;
	char app_name[MAX_APP_ID_LEN] = { 0 };
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	char *caller_pkgid = NULL;

	if (__get_cached_unique_name(pid, app_name, sizeof(app_name),
				&caller_is_app, uid) == false)
		return ERR_ALARM_SYSTEM_FAIL;

	if (!caller_is_app) {
		LOGD("Daemon process is possible to modify alarms[%s]",
				app_name);
		return ALARMMGR_RESULT_SUCCESS;
	} else {
		caller_pkgid = _get_pkgid_by_appid(app_name, uid);
		if (!caller_pkgid) {
			LOGE("Failed to get appinfo %s", app_name);
			return ERR_ALARM_SYSTEM_FAIL;
		}
	}

	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t *)gs_iter->data;
		if (entry->uid == uid && entry->alarm_id == alarm_id &&
				strcmp(caller_pkgid, entry->caller_pkgid) == 0) {
			LOGD("Found alarm of app (uid:%d, pid:%d, caller_pkgid:%s) ", uid, pid, caller_pkgid);

			if (caller_pkgid)
				free(caller_pkgid);
			return ALARMMGR_RESULT_SUCCESS;
		}
	}

	LOGW("[%s] is not permitted to modify alarm_id[%d]", app_name, alarm_id);
	if (caller_pkgid)
		free(caller_pkgid);

	return ERR_ALARM_NOT_PERMITTED_APP;
}

int alarm_manager_alarm_set_rtc_time(GVariant *parameters)
{
	if (_APPFW_FEATURE_WAKEUP_USING_RTC) {
		const char *rtc = default_rtc;
		struct rtc_wkalrm rtc_wkalarm;
		int retval = 0;
		struct tm tm, *alarm_tm = NULL;
		char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
		char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
		/*extract day of the week, day in the year & daylight saving time from system*/
		time_t current_time;
		char buf[1024];
		int year, mon, day, hour, min, sec;
		int return_code = ALARMMGR_RESULT_SUCCESS;

		g_variant_get(parameters, "(iiiiii)", &year, &mon, &day, &hour, &min, &sec);

		current_time = time(NULL);
		alarm_tm = gmtime_r(&current_time, &tm);
		if (alarm_tm == NULL) {
			LOGE("alarm_tm is NULL");
			return ERR_ALARM_SYSTEM_FAIL;
		}

		alarm_tm->tm_year = year;
		alarm_tm->tm_mon = mon;
		alarm_tm->tm_mday = day;
		alarm_tm->tm_hour = hour;
		alarm_tm->tm_min = min;
		alarm_tm->tm_sec = sec;

		/*convert to calendar time representation*/
		time_t rtc_time = mktime(alarm_tm);

		if (gfd < 0) {
			gfd = open(rtc, O_RDWR);
			if (gfd < 0) {
				LOGE("RTC open failed.");
				return ERR_ALARM_SYSTEM_FAIL;
			}
		}

		rtc_wkalarm.enabled = 1;
		rtc_wkalarm.time.tm_year = year;
		rtc_wkalarm.time.tm_mon = mon;
		rtc_wkalarm.time.tm_mday = day;
		rtc_wkalarm.time.tm_hour = hour;
		rtc_wkalarm.time.tm_min = min;
		rtc_wkalarm.time.tm_sec = sec;

		retval = ioctl(gfd, RTC_WKALM_SET, &rtc_wkalarm);
		if (retval == -1) {
			if (errno == ENOTTY)
				LOGE("Alarm IRQs is not supported.");

			LOGE("RTC ALARM_SET ioctl is failed. errno = %s", strerror_r(errno, buf, sizeof(buf)));
			return_code = ERR_ALARM_SYSTEM_FAIL;
			strncpy(log_tag, "FAIL: SET RTC", sizeof(log_tag) - 1);
		} else {
			LOGD("[alarm-server]RTC alarm is setted");
			strncpy(log_tag, "SET RTC", sizeof(log_tag) - 1);
		}

		snprintf(log_message, sizeof(log_message), "wakeup rtc time: %ld, %s", rtc_time, ctime(&rtc_time));
		_save_module_log(log_tag, log_message);
		return return_code;
	} else {
		LOGW("[alarm-server] RTC does not work.");
		return ERR_ALARM_SYSTEM_FAIL;
	}
}

static int accrue_msec = 0; /* To check a millisecond part of current time at changing the system time(sec) */

int alarm_manager_alarm_set_time(GVariant* parameters, pid_t pid)
{
	double diff_time = 0.0;
	struct timeval cur_time = {0,};
	gint64 time_sec;
	time_t new_time;
	char sender_id[MAX_APP_ID_LEN];
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE];

	g_variant_get(parameters, "(x)", &time_sec);

	new_time = (time_t)time_sec;

	_alarm_disable_timer(); /* Disable the timer to reschedule the alarm before the time is changed. */

	tzset();
	gettimeofday(&cur_time, NULL);

	accrue_msec += (cur_time.tv_usec / 1000); /* Accrue the millisecond to compensate the time */
	if (accrue_msec > 500) {
		diff_time = difftime(new_time, cur_time.tv_sec) - 1;
		accrue_msec -= 1000;
	} else {
		diff_time = difftime(new_time, cur_time.tv_sec);
	}

	if (!__set_time(new_time)) { /* Change both OS time and RTC */
		LOGE("Failed to change both OS time and RTC");
		_clear_scheduled_alarm_list();
		_alarm_schedule();
		_rtc_set();
		return ERR_ALARM_SYSTEM_FAIL;
	}

	LOGD("[TIMESTAMP]Current time(%ld), New time(%ld)(%s), diff_time(%f)",
			cur_time.tv_sec, new_time, ctime((const time_t *)&new_time), diff_time);

	__reschedule_alarms_with_newtime(cur_time.tv_sec, new_time, diff_time);

	__get_cached_unique_name(pid, sender_id, MAX_APP_ID_LEN, NULL, 5001);
	snprintf(log_message, sizeof(log_message), "requested by %s (pid %d)", sender_id, pid);
	_save_module_log("SET TIME END", log_message);

	return ALARMMGR_RESULT_SUCCESS;;
}

int alarm_manager_alarm_set_time_with_propagation_delay(GVariant* parameters, pid_t pid)
{
	double diff_time = 0.0;
	struct timespec cur_time = {0,};
	struct timespec delay = {0,};
	struct timespec sleep_time = {0,};
	time_t real_newtime = 0;
	accrue_msec = 0; /* reset accrued msec */
	time_t new_sec, req_sec;
	long new_nsec, req_nsec;
	gint64 tmp_new_sec, tmp_req_sec, tmp_new_nsec, tmp_req_nsec;
	char sender_id[MAX_APP_ID_LEN];
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE];

	g_variant_get(parameters, "(xxxx)", &tmp_new_sec, &tmp_new_nsec, &tmp_req_sec, &tmp_req_nsec);
	new_sec = (time_t)tmp_new_sec;
	new_nsec = (long)tmp_new_nsec;
	req_sec = (time_t)tmp_req_sec;
	req_nsec = (long)tmp_req_nsec;

	_alarm_disable_timer(); /* Disable the timer to reschedule the alarm before the time is changed. */

	tzset();
	clock_gettime(CLOCK_REALTIME, &cur_time);

	/* Check validation of requested time */
	if (req_sec > cur_time.tv_sec || (req_sec == cur_time.tv_sec && req_nsec > cur_time.tv_nsec)) {
		LOGE("The requeted time(%ld.%09ld) must be equal to or less than current time(%ld.%09ld).",
			req_sec, req_nsec, cur_time.tv_sec, cur_time.tv_nsec);
		return ERR_ALARM_INVALID_PARAM;
	}

	/* Compensate propagation delay */
	if (req_nsec > cur_time.tv_nsec) {
		delay.tv_sec = cur_time.tv_sec - 1 - req_sec;
		delay.tv_nsec = cur_time.tv_nsec + BILLION - req_nsec;
	} else {
		delay.tv_sec = cur_time.tv_sec - req_sec;
		delay.tv_nsec = cur_time.tv_nsec - req_nsec;
	}

	if (new_nsec + delay.tv_nsec >= BILLION) {
		real_newtime = new_sec + delay.tv_sec + 2;
		sleep_time.tv_nsec = BILLION - ((delay.tv_nsec + new_nsec) - BILLION);
	} else {
		real_newtime = new_sec + delay.tv_sec + 1;
		sleep_time.tv_nsec = BILLION - (delay.tv_nsec + new_nsec);
	}

	nanosleep(&sleep_time, NULL); /* Wait until 0 nsec to match both OS time and RTC(sec) */

	if (!__set_time(real_newtime)) { /* Change both OS time and RTC */
		LOGE("Failed to change both OS time and RTC");
		_clear_scheduled_alarm_list();
		_alarm_schedule();
		_rtc_set();
		return ERR_ALARM_SYSTEM_FAIL;
	}

	diff_time = difftime(real_newtime, cur_time.tv_sec);
	LOGD("[TIMESTAMP]Current time(%ld.%09ld), New time(%ld.%09ld), Real Newtime(%ld), diff_time(%f)",
		cur_time.tv_sec, cur_time.tv_nsec, new_sec, new_nsec, real_newtime, diff_time);
	LOGD("Requested(%ld.%09ld) Delay(%ld.%09ld) Sleep(%09ld)", req_sec, req_nsec, delay.tv_sec, delay.tv_nsec, sleep_time.tv_nsec);
	__reschedule_alarms_with_newtime(cur_time.tv_sec, real_newtime, diff_time);

	__get_cached_unique_name(pid, sender_id, MAX_APP_ID_LEN, NULL, 5001);
	snprintf(log_message, sizeof(log_message), "requested by %s (pid %d)", sender_id, pid);
	_save_module_log("SET TIME PROPAGATION END", log_message);

	return ALARMMGR_RESULT_SUCCESS;
}

int alarm_manager_alarm_set_timezone(GVariant* parameters)
{
	int retval = 0;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	struct stat statbuf;
	bundle *b = NULL;
	char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
	char *tzpath_str;
	time_t cur_time;

	g_variant_get(parameters, "(&s)", &tzpath_str);

	LOGD("[TIMESTAMP]Set the timezone to %s.", tzpath_str);

	if (lstat(tzpath_str, &statbuf) == -1 && errno == ENOENT) {
		LOGE("Invalid tzpath, %s", tzpath_str);
		return_code = ERR_ALARM_INVALID_PARAM;
		goto done;
	}

	retval = lstat(TIMEZONE_INFO_LINK_PATH, &statbuf);
	if (retval == 0 || (retval == -1 && errno != ENOENT)) {
		/* unlink the current link */
		if (unlink(TIMEZONE_INFO_LINK_PATH) < 0) {
			LOGE("unlink() is failed.");
			return_code = ERR_ALARM_SYSTEM_FAIL;
			goto done;
		}
	}

	/* create a new symlink when the /opt/etc/localtime is empty. */
	if (symlink(tzpath_str, TIMEZONE_INFO_LINK_PATH) < 0) {
		LOGE("Failed to create an symlink of %s.", tzpath_str);
		return_code = ERR_ALARM_SYSTEM_FAIL;
		goto done;
	}

	tzset();

	/* Rescheduling alarms */
	_alarm_disable_timer();
	time(&cur_time);
	__alarm_update_due_time_of_all_items_in_list(cur_time, 0);
	LOGD("next expiring due_time is %ld", alarm_context.c_due_time);

	_clear_scheduled_alarm_list();
	_alarm_schedule();
	_rtc_set();

	vconf_set_int(VCONFKEY_SYSTEM_TIME_CHANGED, 0);
	b = bundle_create();
	bundle_add_str(b, EVT_KEY_TIME_CHANGED, EVT_VAL_TIME_CHANGED_TRUE);
	eventsystem_send_system_event(SYS_EVENT_TIME_CHANGED, b);
	bundle_free(b);

	b = bundle_create();
	bundle_add_str(b, EVT_KEY_TIME_ZONE, tzpath_str);
	eventsystem_send_system_event(SYS_EVENT_TIME_ZONE, b);
	bundle_free(b);

done:
	if (return_code == ALARMMGR_RESULT_SUCCESS)
		strncpy(log_tag, "SET TIMEZONE", sizeof(log_tag) - 1);
	else
		strncpy(log_tag, "FAIL: SET TIMEZONE", sizeof(log_tag) - 1);

	snprintf(log_message, sizeof(log_message), "Set the timezone to %s.", tzpath_str);
	_save_module_log(log_tag, log_message);

	return return_code;
}

int alarm_manager_alarm_create_appsvc(GVariant *parameters, uid_t uid, pid_t pid, int *alarm_id)
{
	alarm_info_t alarm_info;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	int _alarm_id = 0;
	char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
	int result;
	bundle *b;
	const char *callee_appid;
	int start_year, start_month, start_day, start_hour, start_min, start_sec;
	int end_year, end_month, end_day;
	int mode_day_of_week, mode_repeat, alarm_type;
	time_t mode_interval, reserved_info;
	gint64 tmp_mode_interval, tmp_reserved_info;
	char *bundle_data;

	*alarm_id = _alarm_id;
	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(iiiiiiiiiixiix&s)",
			&start_year, &start_month, &start_day, &start_hour, &start_min,
			&start_sec, &end_year, &end_month, &end_day, &mode_day_of_week,
			&tmp_mode_interval, &mode_repeat, &alarm_type, &tmp_reserved_info, &bundle_data);

	mode_interval = (time_t)tmp_mode_interval;
	reserved_info = (time_t)tmp_reserved_info;

	b = bundle_decode((bundle_raw *)bundle_data, strlen(bundle_data));
	if (b == NULL) {
		int ret_bundle = get_last_result();
		LOGE("Failed to decode bundle_data[Error:%d]\n", ret_bundle);
		return ERR_ALARM_SYSTEM_FAIL;
	} else {
		callee_appid = appsvc_get_appid(b);

		if (_compare_api_version(&result, pid, uid) < 0) {
			LOGE("Unable to check api version\n");
			bundle_free(b);
			return ERR_ALARM_SYSTEM_FAIL;
		}

		if (result < 0) {
			if (alarm_type & ALARM_TYPE_INEXACT)
				alarm_type ^= ALARM_TYPE_INEXACT;
		} else { /* Since 2.4 */
			if (!_is_permitted(callee_appid, alarm_type, uid)) {
				LOGE("[%s] is not permitted \n", callee_appid);
				bundle_free(b);
				return ERR_ALARM_NOT_PERMITTED_APP;
			}
		}

		bundle_free(b);
	}

	alarm_info.start.year = start_year;
	alarm_info.start.month = start_month;
	alarm_info.start.day = start_day;
	alarm_info.start.hour = start_hour;
	alarm_info.start.min = start_min;
	alarm_info.start.sec = start_sec;

	alarm_info.end.year = end_year;
	alarm_info.end.month = end_month;
	alarm_info.end.day = end_day;

	alarm_info.mode.u_interval.day_of_week = mode_day_of_week;
	alarm_info.mode.repeat = (alarm_repeat_mode_t)mode_repeat;

	alarm_info.alarm_type = alarm_type;
	alarm_info.reserved_info = reserved_info;

	if ((alarm_info.alarm_type & ALARM_TYPE_INEXACT)) {
		alarm_info.alarm_type |= ALARM_TYPE_PERIOD;
		alarm_info.mode.u_interval.interval =
			__get_proper_interval(mode_interval, alarm_info.alarm_type);
	} else if (mode_interval <= 0) {
		alarm_info.mode.u_interval.interval = 0;
	}

	if (!__alarm_create_appsvc(&alarm_info, &_alarm_id, mode_interval, uid, pid, bundle_data, &return_code)) {
		LOGE("Unable to create alarm! return_code[%d]", return_code);
		strncpy(log_tag, "FAIL: CREATE SVC", sizeof(log_tag) - 1);
		snprintf(log_message, sizeof(log_message),
				"alarmID: %d, uid: %d, pid: %d, duetime: %d-%d-%d %02d:%02d:%02d",
				_alarm_id, uid, pid, start_year, start_month, start_day, start_hour, start_min, start_sec);
		_save_module_log(log_tag, log_message);
		return_code = ERR_ALARM_SYSTEM_FAIL;
	} else {
		*alarm_id = _alarm_id;
		return_code = ALARMMGR_RESULT_SUCCESS;
	}

	return return_code;
}

int alarm_manager_alarm_create_noti(GVariant *parameters, uid_t uid, pid_t pid,
		int *alarm_id)
{
	alarm_info_t alarm_info;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	int _alarm_id = 0;
	char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
	int start_year, start_month, start_day, start_hour, start_min, start_sec;
	int end_year, end_month, end_day;
	int mode_day_of_week, mode_repeat, alarm_type;
	time_t mode_interval, reserved_info;
	gint64 tmp_mode_interval, tmp_reserved_info;
	char *noti_data;

	*alarm_id = _alarm_id;
	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(iiiiiiiiiixiix&s)",
			&start_year, &start_month, &start_day, &start_hour, &start_min,
			&start_sec, &end_year, &end_month, &end_day, &mode_day_of_week,
			&tmp_mode_interval, &mode_repeat, &alarm_type, &tmp_reserved_info, &noti_data);

	mode_interval = (time_t)tmp_mode_interval;
	reserved_info = (time_t)tmp_reserved_info;

	alarm_info.start.year = start_year;
	alarm_info.start.month = start_month;
	alarm_info.start.day = start_day;
	alarm_info.start.hour = start_hour;
	alarm_info.start.min = start_min;
	alarm_info.start.sec = start_sec;

	alarm_info.end.year = end_year;
	alarm_info.end.month = end_month;
	alarm_info.end.day = end_day;

	alarm_info.mode.u_interval.day_of_week = mode_day_of_week;
	alarm_info.mode.repeat = (alarm_repeat_mode_t)mode_repeat;

	alarm_info.alarm_type = alarm_type;
	alarm_info.reserved_info = reserved_info;

	if ((alarm_info.alarm_type & ALARM_TYPE_INEXACT)) {
		alarm_info.alarm_type |= ALARM_TYPE_PERIOD;
		alarm_info.mode.u_interval.interval =
			__get_proper_interval(mode_interval, alarm_info.alarm_type);
	} else if (mode_interval <= 0) {
		alarm_info.mode.u_interval.interval = 0;
	}

	if (!__alarm_create_noti(&alarm_info, &_alarm_id, mode_interval, uid, pid, noti_data, &return_code)) {
		LOGE("Unable to create alarm! return_code[%d]", return_code);
		strncpy(log_tag, "FAIL: CREATE NOTI", sizeof(log_tag) - 1);
		snprintf(log_message, sizeof(log_message), "alarmID: %d, uid: %d, pid: %d, duetime: %d-%d-%d %02d:%02d:%02d",
				_alarm_id, uid, pid, start_year, start_month, start_day, start_hour, start_min, start_sec);
		_save_module_log(log_tag, log_message);
		return_code = ERR_ALARM_SYSTEM_FAIL;
	} else {
		return_code = ALARMMGR_RESULT_SUCCESS;
		*alarm_id = _alarm_id;
	}

	return return_code;
}

int alarm_manager_alarm_create(GVariant *parameters, uid_t uid, pid_t pid, int *alarm_id)
{
	alarm_info_t alarm_info;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	int _alarm_id = 0;
	char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
	char *_reserved_service_name = NULL;
	char *_reserved_service_name_mod = NULL;

	char *app_service_name = NULL;
	char *app_service_name_mod = NULL;
	int start_year, start_month, start_day, start_hour, start_min, start_sec;
	int msec, end_year, end_month, end_day;
	int mode_day_of_week, mode_repeat, alarm_type;
	gint64 tmp_reserved_info;
	time_t reserved_info;
	char *reserved_service_name = NULL;
	char *reserved_service_name_mod = NULL;

	*alarm_id = _alarm_id;
	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(&s&siiiiiiiiiiiiix&s&s)",
			&app_service_name, &app_service_name_mod,
			&start_year, &start_month, &start_day, &start_hour, &start_min,
			&start_sec, &msec, &end_year, &end_month, &end_day,
			&mode_day_of_week, &mode_repeat, &alarm_type, &tmp_reserved_info,
			&reserved_service_name, &reserved_service_name_mod);

	reserved_info = (time_t)tmp_reserved_info;

	alarm_info.start.year = start_year;
	alarm_info.start.month = start_month;
	alarm_info.start.day = start_day;
	alarm_info.start.hour = start_hour;
	alarm_info.start.min = start_min;
	alarm_info.start.sec = start_sec;

	alarm_info.msec = msec;

	alarm_info.end.year = end_year;
	alarm_info.end.month = end_month;
	alarm_info.end.day = end_day;

	alarm_info.mode.u_interval.day_of_week = mode_day_of_week;
	alarm_info.mode.repeat = (alarm_repeat_mode_t)mode_repeat;

	alarm_info.alarm_type = alarm_type;
	alarm_info.reserved_info = reserved_info;

	if (strcmp(reserved_service_name, "null") == 0)
		_reserved_service_name = NULL;
	if (strcmp(reserved_service_name_mod, "null") == 0)
		_reserved_service_name_mod = NULL;

	if (!__alarm_create(&alarm_info, &_alarm_id, uid, pid, QUANTUMIZE, 0, 0, app_service_name, app_service_name_mod,
				_reserved_service_name, _reserved_service_name_mod, &return_code)) {
		LOGE("Unable to create alarm! return_code[%d]", return_code);
		strncpy(log_tag, "FAIL: CREATE", sizeof(log_tag) - 1);
		snprintf(log_message, sizeof(log_message), "alarmID: %d, uid: %d, pid: %d, duetime: %d-%d-%d %02d:%02d:%02d",
				_alarm_id, uid, pid, start_year, start_month, start_day, start_hour, start_min, start_sec);
		_save_module_log(log_tag, log_message);
		return_code = ERR_ALARM_SYSTEM_FAIL;
	} else {
		return_code = ALARMMGR_RESULT_SUCCESS;
		*alarm_id = _alarm_id;
	}

	return return_code;
}

time_t _get_periodic_alarm_standard_time(void)
{
	/* To avoid start time of all devices are same. */
	if (periodic_alarm_standard_time == 0)
		periodic_alarm_standard_time = g_random_int_range(0, BILLION) + 1;

	LOGD("periodic_standard_time : [%ld]", periodic_alarm_standard_time);
	return periodic_alarm_standard_time;
}

int alarm_manager_alarm_create_periodic(GVariant *parameters, uid_t uid,
		pid_t pid, int *alarm_id)
{
	alarm_info_t alarm_info;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	int _alarm_id = 0;
	char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
	char *app_service_name = NULL;
	char *app_service_name_mod = NULL;
	int interval, is_ref, method;

	*alarm_id = _alarm_id;
	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(&s&siii)", &app_service_name,
			&app_service_name_mod, &interval, &is_ref, &method);

	struct tm standard_tm;
	time_t standard_time = _get_periodic_alarm_standard_time();
	localtime_r(&standard_time, &standard_tm);

	alarm_info.reserved_info = standard_time;

	alarm_info.start.year = standard_tm.tm_year + 1900;
	alarm_info.start.month = standard_tm.tm_mon + 1;
	alarm_info.start.day = standard_tm.tm_mday;
	alarm_info.start.hour = standard_tm.tm_hour;
	alarm_info.start.min = standard_tm.tm_min;
	alarm_info.start.sec = standard_tm.tm_sec;

	alarm_info.msec = 0;

	alarm_info.end.year = 0;
	alarm_info.end.month = 0;
	alarm_info.end.day = 0;

	alarm_info.alarm_type = ALARM_TYPE_VOLATILE;
	alarm_info.alarm_type |= ALARM_TYPE_RELATIVE;
	alarm_info.alarm_type |= ALARM_TYPE_WITHCB;
	alarm_info.alarm_type |= ALARM_TYPE_PERIOD;

	if (interval <= 0) {
		alarm_info.mode.repeat = ALARM_REPEAT_MODE_ONCE;
		alarm_info.mode.u_interval.interval = 0;
	} else {
		alarm_info.mode.repeat = ALARM_REPEAT_MODE_REPEAT;
		if (is_ref)
			alarm_info.mode.u_interval.interval = interval * 60;
		else
			alarm_info.mode.u_interval.interval = __get_proper_interval(interval * 60, alarm_info.alarm_type);
	}

	if (!__alarm_create(&alarm_info, &_alarm_id, uid, pid, (periodic_method_e)method, interval * 60, is_ref,
				app_service_name, app_service_name_mod,
				NULL, NULL, &return_code)) {
		LOGE("Unable to create alarm! return_code[%d]", return_code);
		strncpy(log_tag, "FAIL: CREATE PERIODIC", sizeof(log_tag) - 1);
		snprintf(log_message, sizeof(log_message), "alarmID: %d, uid: %d, pid: %d, duetime: %d-%d-%d %02d:%02d:%02d",
				_alarm_id, uid, pid, alarm_info.start.year, alarm_info.start.month,
				alarm_info.start.day, alarm_info.start.hour,
				alarm_info.start.min, alarm_info.start.sec);
		_save_module_log(log_tag, log_message);
		return_code = ERR_ALARM_SYSTEM_FAIL;
	} else {
		return_code = ALARMMGR_RESULT_SUCCESS;
		*alarm_id = _alarm_id;
	}

	return return_code;
}

int alarm_manager_alarm_delete(GVariant *parameters, uid_t uid, pid_t pid)
{
	int return_code = ALARMMGR_RESULT_SUCCESS;
	char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
	int alarm_id;

	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(i)", &alarm_id);

	return_code = __check_modifiable(uid, pid, alarm_id);
	if (return_code != ALARMMGR_RESULT_SUCCESS)
		return return_code;

	if (!__alarm_delete(uid, alarm_id, &return_code)) {
		LOGE("Unable to delete the alarm! alarm_id[%d], return_code[%d]", alarm_id, return_code);
		strncpy(log_tag, "FAIL: DELETE", sizeof(log_tag) - 1);
		return_code = ERR_ALARM_SYSTEM_FAIL;
	} else {
		LOGD("alarm_id[%d] is removed.", alarm_id);
		strncpy(log_tag, "DELETE", sizeof(log_tag) - 1);
		return_code = ALARMMGR_RESULT_SUCCESS;
	}

	snprintf(log_message, sizeof(log_message), "alarmID: %d, uid: %d, pid: %d", alarm_id, uid, pid);
	_save_module_log(log_tag, log_message);

	return return_code;
}

int alarm_manager_alarm_delete_all(GVariant *parameters, uid_t uid, pid_t pid)
{
	GSList *gs_iter = NULL;
	char app_name[MAX_APP_ID_LEN] = { 0 };
	alarm_info_t *alarm_info = NULL;
	__alarm_info_t *entry = NULL;
	bool is_deleted = false;
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};

	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	if (__get_cached_unique_name(pid, app_name, sizeof(app_name), NULL, uid) == false) {
		snprintf(log_message, sizeof(log_message), "pid: %d. Can not get the unique_name.", pid);
		_save_module_log("FAIL: DELETE ALL", log_message);
		return ERR_ALARM_SYSTEM_FAIL;
	}

	SECURE_LOGD("Called by process (pid:%d, unique_name=%s)", pid, app_name);

	for (gs_iter = alarm_context.alarms; gs_iter != NULL;) {
		bool is_found = false;
		entry = (__alarm_info_t*)gs_iter->data;
		const char *tmp_appname = entry->app_unique_name;
		SECURE_LOGD("Try to remove app_name[%s], alarm_id[%d]\n", tmp_appname, entry->alarm_id);
		if (tmp_appname && strncmp(app_name, tmp_appname, strlen(tmp_appname)) == 0) {
			if (_remove_from_scheduled_alarm_list(uid, entry->alarm_id))
				is_deleted = true;

			alarm_info = &entry->alarm_info;
			if (!(alarm_info->alarm_type & ALARM_TYPE_VOLATILE)) {
				if (!_delete_alarms(entry->alarm_id))
					SECURE_LOGE("_delete_alarms() is failed. pid[%d], alarm_id[%d]", pid, entry->alarm_id);
			}
			is_found = true;
		}

		gs_iter = g_slist_next(gs_iter);

		if (is_found) {
			LOGD("alarm_id[%d] is removed.", entry->alarm_id);
			SECURE_LOGD("Removing is done. app_name[%s], alarm_id [%d]\n", tmp_appname, entry->alarm_id);
			alarm_context.alarms = g_slist_remove(alarm_context.alarms, entry);
			_release_alarm_info_t(entry);
		}
	}

	if (is_deleted && (g_slist_length(g_scheduled_alarm_list) == 0)) {
		_alarm_disable_timer();
		_alarm_schedule();
	}

	snprintf(log_message, sizeof(log_message), "uid: %d, pid: %d, unique_name: %s", uid, pid, app_name);
	_save_module_log("DELETE ALL", log_message);

	_rtc_set();
	return ALARMMGR_RESULT_SUCCESS;
}

int alarm_manager_alarm_update(GVariant *parameters, uid_t uid, pid_t pid)
{
	int return_code = ALARMMGR_RESULT_SUCCESS;
	alarm_info_t alarm_info;
	char log_tag[ALARMMGR_LOG_TAG_SIZE] = {0,};
	char log_message[ALARMMGR_LOG_MESSAGE_SIZE] = {0,};
	int alarm_id;
	int start_year, start_month, start_day, start_hour, start_min, start_sec;
	int end_year, end_month, end_day;
	int mode_repeat, alarm_type, update_flag;
	time_t mode_interval, reserved_info;
	gint64 tmp_mode_interval, tmp_reserved_info;

	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(iiiiiiiiiixiixi)",
			&alarm_id, &start_year, &start_month, &start_day, &start_hour,
			&start_min, &start_sec, &end_year, &end_month, &end_day,
			&tmp_mode_interval, &mode_repeat, &alarm_type, &tmp_reserved_info,
			&update_flag);

	mode_interval = (time_t)tmp_mode_interval;
	reserved_info = (time_t)tmp_reserved_info;

	return_code = __check_modifiable(uid, pid, alarm_id);
	if (return_code != ALARMMGR_RESULT_SUCCESS)
		return return_code;

	alarm_info.start.year = start_year;
	alarm_info.start.month = start_month;
	alarm_info.start.day = start_day;
	alarm_info.start.hour = start_hour;
	alarm_info.start.min = start_min;
	alarm_info.start.sec = start_sec;

	alarm_info.end.year = end_year;
	alarm_info.end.month = end_month;
	alarm_info.end.day = end_day;

	alarm_info.mode.u_interval.interval = mode_interval;
	alarm_info.mode.repeat = (alarm_repeat_mode_t)mode_repeat;

	alarm_info.alarm_type = alarm_type;
	alarm_info.reserved_info = reserved_info;

	if (!__alarm_update(uid, alarm_id, &alarm_info,
				update_flag, &return_code)) {
		LOGE("Unable to update the alarm! alarm_id[%d], return_code[%d]", alarm_id, return_code);
		strncpy(log_tag, "FAIL: UPDATE", sizeof(log_tag) - 1);
		snprintf(log_message, sizeof(log_message), "alarmID: %d, uid: %d, pid: %d, duetime: %d-%d-%d %02d:%02d:%02d",
				alarm_id, uid, pid, start_year, start_month, start_day, start_hour, start_min, start_sec);
		_save_module_log(log_tag, log_message);
	}

	return return_code;
}

int alarm_manager_alarm_get_number_of_ids(uid_t uid, pid_t pid, int *num_of_ids)
{
	GSList *gs_iter = NULL;
	char app_name[MAX_APP_ID_LEN] = { 0 };
	__alarm_info_t *entry = NULL;
	int _num_of_ids = 0;

	*num_of_ids = _num_of_ids;
	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	if (__get_cached_unique_name(pid, app_name, sizeof(app_name), NULL, uid) == false)
		return ERR_ALARM_SYSTEM_FAIL;

	SECURE_LOGD("Called by process (uid:%d, pid:%d, unique_name:%s)", uid, pid, app_name);

	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		SECURE_LOGD("app_name=%s, app_unique_name=%s", app_name, entry->app_unique_name);
		if (entry->uid == uid &&
				strncmp(app_name, entry->app_unique_name, strlen(app_name)) == 0) {
			(_num_of_ids)++;
			SECURE_LOGD("inc number of alarms of app (uid:%d, pid:%d, unique_name:%s) is %d.", uid, pid, app_name, _num_of_ids);
		}
	}

	SECURE_LOGD("number of alarms of the process (uid:%d, pid:%d, unique_name:%s) is %d.", uid, pid, app_name, _num_of_ids);
	*num_of_ids = _num_of_ids;
	return ALARMMGR_RESULT_SUCCESS;
}

int alarm_manager_alarm_get_list_of_ids(GVariant *parameters, uid_t uid,
		pid_t pid, GVariant **alarm_array, int *num_of_alarm)
{
	GSList *gs_iter = NULL;
	char app_name[MAX_APP_ID_LEN] = { 0 };
	__alarm_info_t *entry = NULL;
	int index = 0;
	int max_number_of_ids;
	GVariantBuilder *builder = NULL;

	*alarm_array =  g_variant_new("ai", NULL);

	if (uid < 0 || pid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(i)", &max_number_of_ids);

	if (max_number_of_ids <= 0) {
		SECURE_LOGE("called for uid(%d) pid(%d), but max_number_of_ids(%d) is less than 0.", uid, pid, max_number_of_ids);
		*num_of_alarm = 0;
		return ALARMMGR_RESULT_SUCCESS;
	}

	if (__get_cached_unique_name(pid, app_name, sizeof(app_name), NULL, uid) == false)
		return ERR_ALARM_SYSTEM_FAIL;

	SECURE_LOGD("Called by process (uid: %d, pid:%d, unique_name=%s).", uid, pid, app_name);
	builder = g_variant_builder_new(G_VARIANT_TYPE("ai"));

	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		if (entry->uid == uid &&
				strncmp(app_name, (entry->app_unique_name), strlen(app_name)) == 0) {
			g_variant_builder_add(builder, "i", entry->alarm_id);
			index++;
			SECURE_LOGE("called for alarmid(%d), but max_number_of_ids(%d) index %d.", entry->alarm_id, max_number_of_ids, index);
		}
	}

	*alarm_array = g_variant_new("ai", builder);
	*num_of_alarm = index;

	g_variant_builder_unref(builder);
	SECURE_LOGE("Called by uid (%d), pid (%d), but max_number_of_ids(%d).", uid, pid, index);

	return ALARMMGR_RESULT_SUCCESS;
}

int alarm_manager_alarm_get_appsvc_info(GVariant *parameters, uid_t uid, gchar **b_data)
{
	bool found = false;
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	int alarm_id;

	if (uid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(i)", &alarm_id);

	SECURE_LOGD("called for uid(%d), alarm_id(%d)\n", uid, alarm_id);

	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		if (entry->uid == uid && entry->alarm_id == alarm_id) {
			found = true;
			*b_data = g_strdup(entry->bundle);
			break;
		}
	}

	if (found) {
		if (*b_data == NULL) {
			LOGE("The alarm(%d) is an regular alarm, not svc alarm.", alarm_id);
			return_code = ERR_ALARM_INVALID_TYPE;
		}
	} else {
		LOGE("The alarm(%d) is not found.", alarm_id);
		return_code = ERR_ALARM_INVALID_ID;
	}

	return return_code;
}

int alarm_manager_alarm_get_noti_info(GVariant *parameters, uid_t uid, gchar **noti_data)
{
	bool found = false;
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	int alarm_id;

	if (uid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(i)", &alarm_id);

	SECURE_LOGD("called for uid(%d), alarm_id(%d)\n", uid, alarm_id);

	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		if (entry->uid == uid && entry->alarm_id == alarm_id) {
			found = true;
			*noti_data = strdup(entry->noti);
			break;
		}
	}

	if (found) {
		if (*noti_data == NULL) {
			LOGE("The alarm(%d) is an regular alarm, not svc alarm.", alarm_id);
			return_code = ERR_ALARM_INVALID_TYPE;
		}
	} else {
		LOGE("The alarm(%d) is not found.", alarm_id);
		return_code = ERR_ALARM_INVALID_ID;
	}

	return return_code;
}

int alarm_manager_alarm_get_info(GVariant *parameters, uid_t uid, alarm_info_t *alarm_info)
{
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	alarm_info_t *_alarm_info = NULL;
	int alarm_id;

	if (uid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(i)", &alarm_id);

	SECURE_LOGD("called for uid(%d), alarm_id(%d)\n", uid, alarm_id);
	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		if (entry->uid == uid && entry->alarm_id == alarm_id) {
			_alarm_info = &(entry->alarm_info);
			break;
		}
	}

	if (_alarm_info == NULL) {
		LOGE("The alarm(%d) is not found.", alarm_id);
		return ERR_ALARM_INVALID_ID;
	} else {
		LOGD("The alarm(%d) is found.", alarm_id);
		alarm_info->start.year = _alarm_info->start.year;
		alarm_info->start.month = _alarm_info->start.month;
		alarm_info->start.day = _alarm_info->start.day;
		alarm_info->start.hour = _alarm_info->start.hour;
		alarm_info->start.min = _alarm_info->start.min;
		alarm_info->start.sec = _alarm_info->start.sec;
		alarm_info->end.year = _alarm_info->end.year;
		alarm_info->end.month = _alarm_info->end.month;
		alarm_info->end.day = _alarm_info->end.day;
		alarm_info->mode.u_interval.day_of_week =
		  _alarm_info->mode.u_interval.day_of_week;
		alarm_info->mode.repeat = _alarm_info->mode.repeat;
		alarm_info->alarm_type = _alarm_info->alarm_type;
		alarm_info->reserved_info = _alarm_info->reserved_info;
	}

	return ALARMMGR_RESULT_SUCCESS;
}

int alarm_manager_alarm_get_next_duetime(GVariant *parameters, uid_t uid, time_t *duetime)
{
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	__alarm_info_t *find_item = NULL;
	int alarm_id;

	if (uid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(i)", &alarm_id);

	SECURE_LOGD("called for alarm_id(%d)\n", alarm_id);
	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		if (entry->uid == uid && entry->alarm_id == alarm_id) {
			find_item = entry;
			break;
		}
	}

	if (find_item == NULL) {
		LOGE("The alarm(%d) is not found.", alarm_id);
		return ERR_ALARM_INVALID_ID;
	}

	_alarm_set_next_duetime(find_item);
	LOGD("Next duetime : %s", ctime(&(find_item->due_time)));

	*duetime = find_item->due_time;
	return ALARMMGR_RESULT_SUCCESS;
}

int alarm_manager_alarm_get_all_info(uid_t uid, char **db_path)
{
	if (uid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	return _get_db_path_for_all_info(uid, &(*db_path));
}

int alarm_manager_alarm_set_global(GVariant *parameters, uid_t uid)
{
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	alarm_info_t *alarm_info = NULL;
	int retval = 0;
	int return_code = ALARMMGR_RESULT_SUCCESS;
	char *callee_pkgid;
	int alarm_id;
	gboolean global;

	if (uid < 0)
		return ERR_ALARM_SYSTEM_FAIL;

	g_variant_get(parameters, "(ib)", &alarm_id, &global);

	SECURE_LOGD("called for uid(%d), alarm_id(%d)\n", uid, alarm_id);
	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		if (entry->uid == uid && entry->alarm_id == alarm_id) {
			alarm_info = &(entry->alarm_info);
			break;
		}
	}

	if (alarm_info == NULL) {
		LOGE("The alarm(%d) is not found.", alarm_id);
		return ERR_ALARM_INVALID_ID;
	} else {
		LOGD("The alarm(%d) is found.", alarm_id);

		if (entry->callee_pkgid == NULL)
			callee_pkgid = entry->app_service_name + 6;
		else
			callee_pkgid = entry->callee_pkgid;

		LOGD("The alarm pkgid : %s.", callee_pkgid);

		retval = _pkg_is_global(callee_pkgid, uid);
		if (retval == ALARMMGR_RESULT_SUCCESS) {
			entry->global = (bool)global;
			if (!_alarm_set_global_to_db(entry, (bool)global))
				return_code = ERR_ALARM_SYSTEM_FAIL;
		} else {
			LOGE("Get pkginfo error [%d]", retval);
			return_code = retval;
		}
	}

	return return_code;
}

int alarm_manager_alarm_get_global(GVariant *parameters, gboolean *global)
{
	GSList *gs_iter = NULL;
	__alarm_info_t *entry = NULL;
	__alarm_info_t *find_item = NULL;
	int alarm_id;

	g_variant_get(parameters, "(i)", &alarm_id);

	*global = false;
	SECURE_LOGD("called for alarm_id(%d)\n", alarm_id);
	for (gs_iter = alarm_context.alarms; gs_iter != NULL; gs_iter = g_slist_next(gs_iter)) {
		entry = (__alarm_info_t*)gs_iter->data;
		if (entry->alarm_id == alarm_id) {
			find_item = entry;
			break;
		}
	}

	if (find_item == NULL) {
		LOGE("The alarm(%d) is not found.", alarm_id);
		return ERR_ALARM_INVALID_ID;
	}

	*global = (gboolean)find_item->global;
	LOGD("Is global : %d", *global);

	return ALARMMGR_RESULT_SUCCESS;
}

static void __initialize_alarm_list()
{
	alarm_context.alarms = NULL;
	alarm_context.c_due_time = -1;

	_load_alarms_from_db();

	_rtc_set();	/*Set RTC1 Alarm with alarm due time for alarm-manager initialization*/
}

static void __initialize_scheduled_alarm_list()
{
	_clear_scheduled_alarm_list();
}

static void __initialize_noti()
{
	/* VCONFKEY_SYSTEM_TIMECHANGE_EXTERNAL is set by OSP app-service. */
	if (vconf_notify_key_changed
	    (VCONFKEY_SYSTEM_TIMECHANGE_EXTERNAL, __on_system_time_external_changed, NULL) < 0) {
		LOGD("Failed to add callback for time external changing event.");
	}

	/* If the caller or callee app is uninstalled, all registered alarms will be canceled. */
	pkgmgr_client *pc = pkgmgr_client_new(PC_LISTENING);
	pkgmgr_client_set_status_type(pc, PKGMGR_CLIENT_STATUS_UNINSTALL);
	pkgmgr_client_listen_status(pc, __on_app_uninstalled, NULL);

	pkgmgr_client_set_status_type(pc, PKGMGR_CLIENT_STATUS_ENABLE_APP);
	pkgmgr_client_listen_app_status(pc, __on_app_enable_cb, NULL);

	pkgmgr_client_set_status_type(pc, PKGMGR_CLIENT_STATUS_DISABLE_APP);
	pkgmgr_client_listen_app_status(pc, __on_app_disable_cb, NULL);
}

void _alarm_initialize()
{
#if !(GLIB_CHECK_VERSION(2, 36, 0))
	g_type_init();
#endif

	//For debug
	int expire_mode = ALARM_EXPIRE_MODE_NORMAL;
	vconf_get_int(VCONFKEY_ALARM_EXPIRE_MODE, &expire_mode);
	LOGD("alarm_expire_mode : %d", expire_mode);

	alarm_context.timer = _initialize_timer();
	if (alarm_context.timer == -1) {
		LOGE("because _initialize_timer failed, "
					  "alarm-server cannot be runned.\n");
		exit(1);
	}

	if (_initialize_dbus() == false) {
		/* because dbus's initialize
		 * failed, we cannot continue any more. */
		LOGE("because _initialize_dbus failed, "
					  "alarm-server cannot be runned.\n");
		exit(1);
	}

	_initialize_module_log(); /* for module log */

	__initialize_scheduled_alarm_list();
	if (_initialize_db() == false) {
		LOGE("_initialize_db failed, "
				"alarm cannot be stored to database.\n");
	}
	__initialize_alarm_list();
	__initialize_noti();

	if (!caller_appid_cache_table) {
		caller_appid_cache_table = g_hash_table_new_full(g_direct_hash,
				g_direct_equal, NULL, __free_cached_value);
	}
}

void _release_alarm_info_t(__alarm_info_t *entry)
{
	if (!entry)
		return;

	if (entry->caller_pkgid)
		free(entry->caller_pkgid);
	if (entry->callee_pkgid)
		free(entry->callee_pkgid);
	if (entry->app_unique_name)
		free(entry->app_unique_name);
	if (entry->app_service_name)
		free(entry->app_service_name);
	if (entry->app_service_name_mod)
		free(entry->app_service_name_mod);
	if (entry->dst_service_name)
		free(entry->dst_service_name);

	if (entry->dst_service_name_mod)
		free(entry->dst_service_name_mod);
	if (entry->bundle)
		free(entry->bundle);
	if (entry->noti)
		free(entry->noti);

	free(entry);
}