summaryrefslogtreecommitdiff
path: root/toolkit/mozapps/update/nsUpdateService.js
blob: 9214eb7b4ce5d0b7a83c4590f457061ae0401937 (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
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
#filter substitution

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/AddonManager.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/ctypes.jsm");
#ifdef MOZ_SERVICES_HEALTHREPORT
Components.utils.import("resource://gre/modules/UpdaterHealthProvider.jsm");
#endif

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;

const UPDATESERVICE_CID = Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}");
const UPDATESERVICE_CONTRACTID = "@mozilla.org/updates/update-service;1";

const PREF_APP_UPDATE_ALTWINDOWTYPE       = "app.update.altwindowtype";
const PREF_APP_UPDATE_AUTO                = "app.update.auto";
const PREF_APP_UPDATE_BACKGROUND_INTERVAL = "app.update.download.backgroundInterval";
const PREF_APP_UPDATE_BACKGROUNDERRORS    = "app.update.backgroundErrors";
const PREF_APP_UPDATE_BACKGROUNDMAXERRORS = "app.update.backgroundMaxErrors";
const PREF_APP_UPDATE_CERTS_BRANCH        = "app.update.certs.";
const PREF_APP_UPDATE_CERT_CHECKATTRS     = "app.update.cert.checkAttributes";
const PREF_APP_UPDATE_CERT_ERRORS         = "app.update.cert.errors";
const PREF_APP_UPDATE_CERT_MAXERRORS      = "app.update.cert.maxErrors";
const PREF_APP_UPDATE_CERT_REQUIREBUILTIN = "app.update.cert.requireBuiltIn";
const PREF_APP_UPDATE_CUSTOM              = "app.update.custom";
const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
const PREF_APP_UPDATE_METRO_ENABLED       = "app.update.metro.enabled";
const PREF_APP_UPDATE_IDLETIME            = "app.update.idletime";
const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
const PREF_APP_UPDATE_LASTUPDATETIME      = "app.update.lastUpdateTime.background-update-timer";
const PREF_APP_UPDATE_LOG                 = "app.update.log";
const PREF_APP_UPDATE_MODE                = "app.update.mode";
const PREF_APP_UPDATE_NEVER_BRANCH        = "app.update.never.";
const PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED = "app.update.notifiedUnsupported";
const PREF_APP_UPDATE_POSTUPDATE          = "app.update.postupdate";
const PREF_APP_UPDATE_PROMPTWAITTIME      = "app.update.promptWaitTime";
const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
const PREF_APP_UPDATE_SILENT              = "app.update.silent";
const PREF_APP_UPDATE_STAGING_ENABLED     = "app.update.staging.enabled";
const PREF_APP_UPDATE_URL                 = "app.update.url";
const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
const PREF_APP_UPDATE_SOCKET_ERRORS       = "app.update.socket.maxErrors";
const PREF_APP_UPDATE_RETRY_TIMEOUT       = "app.update.socket.retryTimeout";

const PREF_APP_DISTRIBUTION               = "distribution.id";
const PREF_APP_DISTRIBUTION_VERSION       = "distribution.version";

const PREF_APP_B2G_VERSION                = "b2g.version";

const PREF_EM_HOTFIX_ID                   = "extensions.hotfix.id";

const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";

const CATEGORY_UPDATE_TIMER               = "update-timer";

const KEY_GRED            = "GreD";
const KEY_UPDROOT         = "UpdRootD";
const KEY_EXECUTABLE      = "XREExeF";

#ifdef MOZ_WIDGET_GONK
#define USE_UPDATE_ARCHIVE_DIR
#endif

#ifdef USE_UPDATE_ARCHIVE_DIR
const KEY_UPDATE_ARCHIVE_DIR = "UpdArchD"
#endif

const DIR_UPDATES         = "updates";
#ifdef XP_MACOSX
const UPDATED_DIR         = "Updated.app";
#else
const UPDATED_DIR         = "updated";
#endif
const FILE_UPDATE_STATUS  = "update.status";
const FILE_UPDATE_VERSION = "update.version";
#ifdef MOZ_WIDGET_ANDROID
const FILE_UPDATE_ARCHIVE = "update.apk";
#else
const FILE_UPDATE_ARCHIVE = "update.mar";
#endif
const FILE_UPDATE_LINK    = "update.link";
const FILE_UPDATE_LOG     = "update.log";
const FILE_UPDATES_DB     = "updates.xml";
const FILE_UPDATE_ACTIVE  = "active-update.xml";
const FILE_PERMS_TEST     = "update.test";
const FILE_LAST_LOG       = "last-update.log";
const FILE_BACKUP_LOG     = "backup-update.log";
const FILE_UPDATE_LOCALE  = "update.locale";

const STATE_NONE            = "null";
const STATE_DOWNLOADING     = "downloading";
const STATE_PENDING         = "pending";
const STATE_APPLYING        = "applying";
const STATE_APPLIED         = "applied";
const STATE_APPLIED_OS      = "applied-os";
const STATE_SUCCEEDED       = "succeeded";
const STATE_DOWNLOAD_FAILED = "download-failed";
const STATE_FAILED          = "failed";

// From updater/errors.h:
const WRITE_ERROR        = 7;
// const UNEXPECTED_ERROR   = 8; // Replaced with errors 38-42
const ELEVATION_CANCELED = 9;

const WRITE_ERROR_ACCESS_DENIED                     = 35;
// const WRITE_ERROR_SHARING_VIOLATION                 = 36; // Replaced with errors 46-48
const WRITE_ERROR_CALLBACK_APP                      = 37;
const INVALID_UPDATER_STATUS_CODE                   = 38;
const UNEXPECTED_BZIP_ERROR                         = 39;
const UNEXPECTED_MAR_ERROR                          = 40;
const UNEXPECTED_BSPATCH_ERROR                      = 41;
const UNEXPECTED_FILE_OPERATION_ERROR               = 42;
const FILESYSTEM_MOUNT_READWRITE_ERROR              = 43;
const FOTA_GENERAL_ERROR                            = 44;
const FOTA_UNKNOWN_ERROR                            = 45;
const WRITE_ERROR_SHARING_VIOLATION_SIGNALED        = 46;
const WRITE_ERROR_SHARING_VIOLATION_NOPROCESSFORPID = 47;
const WRITE_ERROR_SHARING_VIOLATION_NOPID           = 48;
const FOTA_FILE_OPERATION_ERROR                     = 49;
const FOTA_RECOVERY_ERROR                           = 50;

const CERT_ATTR_CHECK_FAILED_NO_UPDATE  = 100;
const CERT_ATTR_CHECK_FAILED_HAS_UPDATE = 101;
const BACKGROUNDCHECK_MULTIPLE_FAILURES = 110;
const NETWORK_ERROR_OFFLINE             = 111;
const FILE_ERROR_TOO_BIG                = 112;

// Error codes should be < 1000. Errors above 1000 represent http status codes
const HTTP_ERROR_OFFSET                 = 1000;

const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
const DOWNLOAD_FOREGROUND_INTERVAL  = 0;

const UPDATE_WINDOW_NAME      = "Update:Wizard";

// The number of consecutive failures when updating using the service before
// setting the app.update.service.enabled preference to false.
const DEFAULT_SERVICE_MAX_ERRORS = 10;

// The number of consecutive socket errors to allow before falling back to
// downloading a different MAR file or failing if already downloading the full.
const DEFAULT_SOCKET_MAX_ERRORS = 10;

// The number of milliseconds to wait before retrying a connection error.
const DEFAULT_UPDATE_RETRY_TIMEOUT = 2000;

// A background download is in progress (no notification)
const PING_BGUC_IS_DOWNLOADING               = 0;
// An update is staged (no notification)
const PING_BGUC_IS_STAGED                    = 1;
// Invalid url for app.update.url default preference (no notification)
const PING_BGUC_INVALID_DEFAULT_URL          = 2;
// Invalid url for app.update.url user preference (no notification)
const PING_BGUC_INVALID_CUSTOM_URL           = 3;
// Invalid url for app.update.url.override user preference (no notification)
const PING_BGUC_INVALID_OVERRIDE_URL         = 4;
// Unable to check for updates per gCanCheckForUpdates and hasUpdateMutex()
// (no notification)
const PING_BGUC_UNABLE_TO_CHECK              = 5;
// Already has an active update in progress (no notification)
const PING_BGUC_HAS_ACTIVEUPDATE             = 6;
// Background checks disabled by preference (no notification)
const PING_BGUC_PREF_DISABLED                = 7;
// Background checks disabled for the current session (no notification)
const PING_BGUC_DISABLED_FOR_SESSION         = 8;
// Background checks disabled in Metro (no notification)
const PING_BGUC_METRO_DISABLED               = 9;
// Unable to perform a background check while offline (no notification)
const PING_BGUC_OFFLINE                      = 10;
// No update found certificate check failed and threshold reached
// (possible mitm attack notification)
const PING_BGUC_CERT_ATTR_NO_UPDATE_NOTIFY   = 11;
// No update found certificate check failed and threshold not reached
// (no notification)
const PING_BGUC_CERT_ATTR_NO_UPDATE_SILENT   = 12;
// Update found certificate check failed and threshold reached
// (possible mitm attack notification)
const PING_BGUC_CERT_ATTR_WITH_UPDATE_NOTIFY = 13;
// Update found certificate check failed and threshold not reached
// (no notification)
const PING_BGUC_CERT_ATTR_WITH_UPDATE_SILENT = 14;
// General update check failure and threshold reached
// (check failure notification)
const PING_BGUC_GENERAL_ERROR_NOTIFY         = 15;
// General update check failure and threshold not reached
// (no notification)
const PING_BGUC_GENERAL_ERROR_SILENT         = 16;
// No update found (no notification)
const PING_BGUC_NO_UPDATE_FOUND              = 17;
// No compatible update found though there were updates (no notification)
const PING_BGUC_NO_COMPAT_UPDATE_FOUND       = 18;
// Update found for a previous version (no notification)
const PING_BGUC_UPDATE_PREVIOUS_VERSION      = 19;
// Update found for a version with the never preference set (no notification)
const PING_BGUC_UPDATE_NEVER_PREF            = 20;
// Update found without a type attribute (no notification)
const PING_BGUC_UPDATE_INVALID_TYPE          = 21;
// The system is no longer supported (system unsupported notification)
const PING_BGUC_UNSUPPORTED                  = 22;
// Unable to apply updates (manual install to update notification)
const PING_BGUC_UNABLE_TO_APPLY              = 23;
// Showing prompt due to the update.xml specifying showPrompt
// (update notification)
const PING_BGUC_SHOWPROMPT_SNIPPET           = 24;
// Showing prompt due to preference (update notification)
const PING_BGUC_SHOWPROMPT_PREF              = 25;
// Incompatible add-on check disabled by preference (background download)
const PING_BGUC_ADDON_PREF_DISABLED          = 26;
// Incompatible add-on not checked not performed due to same update version and
// app version (background download)
const PING_BGUC_ADDON_SAME_APP_VER           = 27;
// No incompatible add-ons found during incompatible check (background download)
const PING_BGUC_CHECK_NO_INCOMPAT            = 28;
// Incompatible add-ons found and all of them have updates (background download)
const PING_BGUC_ADDON_UPDATES_FOR_INCOMPAT   = 29;
// Incompatible add-ons found (update notification)
const PING_BGUC_ADDON_HAVE_INCOMPAT          = 30;

// Health report field names
const UpdaterHealthReportFields = {
  CHECK_START: "updateCheckStart",
  CHECK_SUCCESS: "updateCheckSuccess",
  CHECK_FAILED: "updateCheckFailed",
  COMPLETE_START: "completeUpdateStart",
  PARTIAL_START: "partialUpdateStart",
  COMPLETE_SUCCESS: "completeUpdateSuccess",
  PARTIAL_SUCCESS: "partialUpdateSuccess",
  FAILED: "updateFailed"
};

var gLocale = null;
var gUpdateMutexHandle = null;

#ifdef MOZ_WIDGET_GONK
var gSDCardMountLock = null;

XPCOMUtils.defineLazyGetter(this, "gExtStorage", function aus_gExtStorage() {
    return Services.env.get("EXTERNAL_STORAGE");
});
#endif

XPCOMUtils.defineLazyModuleGetter(this, "UpdateChannel",
                                  "resource://gre/modules/UpdateChannel.jsm");

XPCOMUtils.defineLazyGetter(this, "gLogEnabled", function aus_gLogEnabled() {
  return getPref("getBoolPref", PREF_APP_UPDATE_LOG, false);
});

XPCOMUtils.defineLazyGetter(this, "gUpdateBundle", function aus_gUpdateBundle() {
  return Services.strings.createBundle(URI_UPDATES_PROPERTIES);
});

// shared code for suppressing bad cert dialogs
XPCOMUtils.defineLazyGetter(this, "gCertUtils", function aus_gCertUtils() {
  let temp = { };
  Cu.import("resource://gre/modules/CertUtils.jsm", temp);
  return temp;
});

XPCOMUtils.defineLazyGetter(this, "gABI", function aus_gABI() {
  let abi = null;
  try {
    abi = Services.appinfo.XPCOMABI;
  }
  catch (e) {
    LOG("gABI - XPCOM ABI unknown: updates are not possible.");
  }
#ifdef XP_MACOSX
  // Mac universal build should report a different ABI than either macppc
  // or mactel.
  let macutils = Cc["@mozilla.org/xpcom/mac-utils;1"].
                 getService(Ci.nsIMacUtils);

  if (macutils.isUniversalBinary)
    abi += "-u-" + macutils.architecturesInBinary;
#ifdef MOZ_SHARK
  // Disambiguate optimised and shark nightlies
  abi += "-shark"
#endif
#endif
  return abi;
});

#ifdef MOZ_WIDGET_GONK
XPCOMUtils.defineLazyGetter(this, "gProductModel", function aus_gProductModel() {
  Cu.import("resource://gre/modules/systemlibs.js");
  return libcutils.property_get("ro.product.model");
});
XPCOMUtils.defineLazyGetter(this, "gProductDevice", function aus_gProductDevice() {
  Cu.import("resource://gre/modules/systemlibs.js");
  return libcutils.property_get("ro.product.device");
});
#endif

XPCOMUtils.defineLazyGetter(this, "gOSVersion", function aus_gOSVersion() {
  let osVersion;
  let sysInfo = Cc["@mozilla.org/system-info;1"].
                getService(Ci.nsIPropertyBag2);
  try {
    osVersion = sysInfo.getProperty("name") + " " + sysInfo.getProperty("version");
  }
  catch (e) {
    LOG("gOSVersion - OS Version unknown: updates are not possible.");
  }

  if (osVersion) {
#ifdef XP_WIN
    const BYTE = ctypes.uint8_t;
    const WORD = ctypes.uint16_t;
    const DWORD = ctypes.uint32_t;
    const WCHAR = ctypes.char16_t;
    const BOOL = ctypes.int;

    // This structure is described at:
    // http://msdn.microsoft.com/en-us/library/ms724833%28v=vs.85%29.aspx
    const SZCSDVERSIONLENGTH = 128;
    const OSVERSIONINFOEXW = new ctypes.StructType('OSVERSIONINFOEXW',
        [
        {dwOSVersionInfoSize: DWORD},
        {dwMajorVersion: DWORD},
        {dwMinorVersion: DWORD},
        {dwBuildNumber: DWORD},
        {dwPlatformId: DWORD},
        {szCSDVersion: ctypes.ArrayType(WCHAR, SZCSDVERSIONLENGTH)},
        {wServicePackMajor: WORD},
        {wServicePackMinor: WORD},
        {wSuiteMask: WORD},
        {wProductType: BYTE},
        {wReserved: BYTE}
        ]);

    // This structure is described at:
    // http://msdn.microsoft.com/en-us/library/ms724958%28v=vs.85%29.aspx
    const SYSTEM_INFO = new ctypes.StructType('SYSTEM_INFO',
        [
        {wProcessorArchitecture: WORD},
        {wReserved: WORD},
        {dwPageSize: DWORD},
        {lpMinimumApplicationAddress: ctypes.voidptr_t},
        {lpMaximumApplicationAddress: ctypes.voidptr_t},
        {dwActiveProcessorMask: DWORD.ptr},
        {dwNumberOfProcessors: DWORD},
        {dwProcessorType: DWORD},
        {dwAllocationGranularity: DWORD},
        {wProcessorLevel: WORD},
        {wProcessorRevision: WORD}
        ]);

    let kernel32 = false;
    try {
      kernel32 = ctypes.open("Kernel32");
    } catch (e) {
      LOG("gOSVersion - Unable to open kernel32! " + e);
      osVersion += ".unknown (unknown)";
    }

    if(kernel32) {
      try {
        // Get Service pack info
        try {
          let GetVersionEx = kernel32.declare("GetVersionExW",
                                              ctypes.default_abi,
                                              BOOL,
                                              OSVERSIONINFOEXW.ptr);
          let winVer = OSVERSIONINFOEXW();
          winVer.dwOSVersionInfoSize = OSVERSIONINFOEXW.size;

          if(0 !== GetVersionEx(winVer.address())) {
            osVersion += "." + winVer.wServicePackMajor
                      +  "." + winVer.wServicePackMinor;
          } else {
            LOG("gOSVersion - Unknown failure in GetVersionEX (returned 0)");
            osVersion += ".unknown";
          }
        } catch (e) {
          LOG("gOSVersion - error getting service pack information. Exception: " + e);
          osVersion += ".unknown";
        }

        // Get processor architecture
        let arch = "unknown";
        try {
          let GetNativeSystemInfo = kernel32.declare("GetNativeSystemInfo",
                                                     ctypes.default_abi,
                                                     ctypes.void_t,
                                                     SYSTEM_INFO.ptr);
          let sysInfo = SYSTEM_INFO();
          // Default to unknown
          sysInfo.wProcessorArchitecture = 0xffff;

          GetNativeSystemInfo(sysInfo.address());
          switch(sysInfo.wProcessorArchitecture) {
            case 9:
              arch = "x64";
              break;
            case 6:
              arch = "IA64";
              break;
            case 0:
              arch = "x86";
              break;
          }
        } catch (e) {
          LOG("gOSVersion - error getting processor architecture.  Exception: " + e);
        } finally {
          osVersion += " (" + arch + ")";
        }
      } finally {
        kernel32.close();
      }
    }
#endif

    try {
      osVersion += " (" + sysInfo.getProperty("secondaryLibrary") + ")";
    }
    catch (e) {
      // Not all platforms have a secondary widget library, so an error is nothing to worry about.
    }
    osVersion = encodeURIComponent(osVersion);
  }
  return osVersion;
});

/**
 * Tests to make sure that we can write to a given directory.
 *
 * @param updateTestFile a test file in the directory that needs to be tested.
 * @param createDirectory whether a test directory should be created.
 * @throws if we don't have right access to the directory.
 */
function testWriteAccess(updateTestFile, createDirectory) {
  const NORMAL_FILE_TYPE = Ci.nsILocalFile.NORMAL_FILE_TYPE;
  const DIRECTORY_TYPE = Ci.nsILocalFile.DIRECTORY_TYPE;
  if (updateTestFile.exists())
    updateTestFile.remove(false);
  updateTestFile.create(createDirectory ? DIRECTORY_TYPE : NORMAL_FILE_TYPE,
                        createDirectory ? FileUtils.PERMS_DIRECTORY : FileUtils.PERMS_FILE);
  updateTestFile.remove(false);
}

#ifdef XP_WIN

/**
 * Closes a Win32 handle
 *
 * @param handle The handle to close
 */
function closeHandle(handle) {
  var lib = ctypes.open("kernel32.dll");
  var CloseHandle = lib.declare("CloseHandle",
                                ctypes.winapi_abi,
                                ctypes.int32_t, /* success */
                                ctypes.void_t.ptr); /* handle */
  CloseHandle(handle);
  lib.close();
}

/**
 * Creates a mutex.
 *
 * @param  aName
 *         The name for the mutex.
 * @param  aAllowExisting
 *         If false the function will close the handle and return null.
 * @return The Win32 handle to the mutex.
 */
function createMutex(aName, aAllowExisting) {
  if (aAllowExisting === undefined) {
    aAllowExisting = true;
  }

  const INITIAL_OWN = 1;
  const ERROR_ALREADY_EXISTS = 0xB7;
  var lib = ctypes.open("kernel32.dll");
  var CreateMutexW = lib.declare("CreateMutexW",
                                 ctypes.winapi_abi,
                                 ctypes.void_t.ptr, /* return handle */
                                 ctypes.void_t.ptr, /* security attributes */
                                 ctypes.int32_t, /* initial owner */
                                 ctypes.char16_t.ptr); /* name */

  var handle = CreateMutexW(null, INITIAL_OWN, aName);
  var alreadyExists = ctypes.winLastError == ERROR_ALREADY_EXISTS;
  if (handle && !handle.isNull() && !aAllowExisting && alreadyExists) {
    closeHandle(handle);
    handle = null;
  }
  lib.close();

  if (handle && handle.isNull())
    handle = null;

  return handle;
}

/**
 * Determines a unique mutex name for the installation
 *
 * @param aGlobal true if the function should return a global mutex. A global
 *                mutex is valid across different sessions
 * @return Global mutex path
 */
function getPerInstallationMutexName(aGlobal) {
  if (aGlobal === undefined) {
    aGobal = true;
  }
  let hasher = Cc["@mozilla.org/security/hash;1"].
               createInstance(Ci.nsICryptoHash);
  hasher.init(hasher.SHA1);

  var exeFile = Services.dirsvc.get(KEY_EXECUTABLE, Ci.nsILocalFile);

  let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
                  createInstance(Ci.nsIScriptableUnicodeConverter);
  converter.charset = "UTF-8";
  var data = converter.convertToByteArray(exeFile.path.toLowerCase());

  hasher.update(data, data.length);
  return (aGlobal ? "Global\\" : "") + "MozillaUpdateMutex-" + hasher.finish(true);
}
#endif // XP_WIN

/**
 * Whether or not the current instance has the update mutex. The update mutex
 * gives protection against 2 applications from the same installation updating:
 * 1) Running multiple profiles from the same installation path
 * 2) Running a Metro and Desktop application at the same time from the same
 *    path
 * 3) 2 applications running in 2 different user sessions from the same path
 *
 * @return true if this instance holds the update mutex
 */
function hasUpdateMutex() {
#ifdef XP_WIN
  if (!gUpdateMutexHandle) {
    gUpdateMutexHandle = createMutex(getPerInstallationMutexName(true), false);
  }

  return !!gUpdateMutexHandle;
#else
  return true;
#endif // XP_WIN
}

function getCanApplyUpdates() {
  function submitHasPermissionsTelemetryPing(val) {
    try {
      let h = Services.telemetry.getHistogramById("UPDATER_HAS_PERMISSIONS");
      h.add(+val);
    } catch(e) {
      // Don't allow any exception to be propagated.
      Components.utils.reportError(e);
    }
  }

  try {
    var updateTestFile = getUpdateFile([FILE_PERMS_TEST]);
    LOG("getCanApplyUpdates - testing write access " + updateTestFile.path);
    testWriteAccess(updateTestFile, false);
#ifdef XP_MACOSX
    // Check that the application bundle can be written to.
    var appDirTestFile = getAppBaseDir();
    appDirTestFile.append(FILE_PERMS_TEST);
    LOG("getCanApplyUpdates - testing write access " + appDirTestFile.path);
    if (appDirTestFile.exists()) {
      appDirTestFile.remove(false)
    }
    appDirTestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
    appDirTestFile.remove(false);
#elifdef XP_WIN
    var sysInfo = Cc["@mozilla.org/system-info;1"].
                  getService(Ci.nsIPropertyBag2);

    // Example windowsVersion:  Windows XP == 5.1
    var windowsVersion = sysInfo.getProperty("version");
    LOG("getCanApplyUpdates - windowsVersion = " + windowsVersion);

  /**
#    For Vista, updates can be performed to a location requiring admin
#    privileges by requesting elevation via the UAC prompt when launching
#    updater.exe if the appDir is under the Program Files directory
#    (e.g. C:\Program Files\) and UAC is turned on and  we can elevate
#    (e.g. user has a split token).
#
#    Note: this does note attempt to handle the case where UAC is turned on
#    and the installation directory is in a restricted location that
#    requires admin privileges to update other than Program Files.
   */
    var userCanElevate = false;

    if (parseFloat(windowsVersion) >= 6) {
      try {
        var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
                          getService(Ci.nsIProperties);
        // KEY_UPDROOT will fail and throw an exception if
        // appDir is not under the Program Files, so we rely on that
        var dir = fileLocator.get(KEY_UPDROOT, Ci.nsIFile);
        // appDir is under Program Files, so check if the user can elevate
        userCanElevate = Services.appinfo.QueryInterface(Ci.nsIWinAppHelper).
                         userCanElevate;
        LOG("getCanApplyUpdates - on Vista, userCanElevate: " + userCanElevate);
      }
      catch (ex) {
        // When the installation directory is not under Program Files,
        // fall through to checking if write access to the
        // installation directory is available.
        LOG("getCanApplyUpdates - on Vista, appDir is not under Program Files");
      }
    }

    /**
#      On Windows, we no longer store the update under the app dir.
#
#      If we are on Windows (including Vista, if we can't elevate) we need to
#      to check that we can create and remove files from the actual app
#      directory (like C:\Program Files\Mozilla Firefox).  If we can't
#      (because this user is not an adminstrator, for example) canUpdate()
#      should return false.
#
#      For Vista, we perform this check to enable updating the  application
#      when the user has write access to the installation directory under the
#      following scenarios:
#      1) the installation directory is not under Program Files
#         (e.g. C:\Program Files)
#      2) UAC is turned off
#      3) UAC is turned on and the user is not an admin
#         (e.g. the user does not have a split token)
#      4) UAC is turned on and the user is already elevated, so they can't be
#         elevated again
     */
    if (!userCanElevate) {
      // if we're unable to create the test file this will throw an exception.
      var appDirTestFile = getAppBaseDir();
      appDirTestFile.append(FILE_PERMS_TEST);
      LOG("getCanApplyUpdates - testing write access " + appDirTestFile.path);
      if (appDirTestFile.exists())
        appDirTestFile.remove(false)
      appDirTestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
      appDirTestFile.remove(false);
    }
#endif //XP_WIN
  }
  catch (e) {
     LOG("getCanApplyUpdates - unable to apply updates. Exception: " + e);
    // No write privileges to install directory
    submitHasPermissionsTelemetryPing(false);
    return false;
  }

  LOG("getCanApplyUpdates - able to apply updates");
  submitHasPermissionsTelemetryPing(true);
  return true;
}

/**
 * Whether or not the application can stage an update.
 *
 * @return true if updates can be staged.
 */
function getCanStageUpdates() {
  // If background updates are disabled, then just bail out!
  if (!getPref("getBoolPref", PREF_APP_UPDATE_STAGING_ENABLED, false)) {
    LOG("getCanStageUpdates - staging updates is disabled by preference " +
        PREF_APP_UPDATE_STAGING_ENABLED);
    return false;
  }

#ifdef MOZ_WIDGET_GONK
  // For Gonk, the updater will remount the /system partition to move staged
  // files into place.
  if (getPref("getBoolPref", PREF_APP_UPDATE_SERVICE_ENABLED, false)) {
    LOG("getCanStageUpdates - able to stage updates because this is gonk");
    return true;
  }
#endif

  if (!hasUpdateMutex()) {
    LOG("getCanStageUpdates - unable to apply updates because another " +
        "instance of the application is already handling updates for this " +
        "installation.");
    return false;
  }

  /**
   * Whether or not the application can stage an update for the current session.
   * These checks are only performed once per session due to using a lazy getter.
   *
   * @return true if updates can be staged for this session.
   */
  XPCOMUtils.defineLazyGetter(this, "canStageUpdatesSession", function canStageUpdatesSession() {
    try {
      var updateTestFile = getInstallDirRoot();
      updateTestFile.append(FILE_PERMS_TEST);
      LOG("canStageUpdatesSession - testing write access " +
          updateTestFile.path);
      testWriteAccess(updateTestFile, true);
#ifndef XP_MACOSX
      // On all platforms except Mac, we need to test the parent directory as
      // well, as we need to be able to move files in that directory during the
      // replacing step.
      updateTestFile = getInstallDirRoot().parent;
      updateTestFile.append(FILE_PERMS_TEST);
      LOG("canStageUpdatesSession - testing write access " +
          updateTestFile.path);
      updateTestFile.createUnique(Ci.nsILocalFile.DIRECTORY_TYPE,
                                  FileUtils.PERMS_DIRECTORY);
      updateTestFile.remove(false);
#endif
    }
    catch (e) {
       LOG("canStageUpdatesSession - unable to stage updates. Exception: " +
           e);
      // No write privileges
      return false;
    }

    LOG("canStageUpdatesSession - able to stage updates");
    return true;
  });

  return canStageUpdatesSession;
}

XPCOMUtils.defineLazyGetter(this, "gMetroUpdatesEnabled", function aus_gMetroUpdatesEnabled() {
#ifdef XP_WIN
#ifdef MOZ_METRO
  if (Services.metro && Services.metro.immersive) {
    let metroUpdate = getPref("getBoolPref", PREF_APP_UPDATE_METRO_ENABLED, true);
    if (!metroUpdate) {
      LOG("gMetroUpdatesEnabled - unable to automatically check for metro " +
          "updates, disabled by pref");
      return false;
    }
  }
#endif
#endif

  return true;
});

XPCOMUtils.defineLazyGetter(this, "gCanCheckForUpdates", function aus_gCanCheckForUpdates() {
  // If the administrator has disabled app update and locked the preference so
  // users can't check for updates. This preference check is ok in this lazy
  // getter since locked prefs don't change until the application is restarted.
  var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  if (!enabled && Services.prefs.prefIsLocked(PREF_APP_UPDATE_ENABLED)) {
    LOG("gCanCheckForUpdates - unable to automatically check for updates, " +
        "the preference is disabled and admistratively locked.");
    return false;
  }

  if (!gMetroUpdatesEnabled) {
    return false;
  }

  // If we don't know the binary platform we're updating, we can't update.
  if (!gABI) {
    LOG("gCanCheckForUpdates - unable to check for updates, unknown ABI");
    return false;
  }

  // If we don't know the OS version we're updating, we can't update.
  if (!gOSVersion) {
    LOG("gCanCheckForUpdates - unable to check for updates, unknown OS " +
        "version");
    return false;
  }

  LOG("gCanCheckForUpdates - able to check for updates");
  return true;
});

/**
 * Logs a string to the error console.
 * @param   string
 *          The string to write to the error console.
 */
function LOG(string) {
  if (gLogEnabled) {
    dump("*** AUS:SVC " + string + "\n");
    Services.console.logStringMessage("AUS:SVC " + string);
  }
}

/**
#  Gets a preference value, handling the case where there is no default.
#  @param   func
#           The name of the preference function to call, on nsIPrefBranch
#  @param   preference
#           The name of the preference
#  @param   defaultValue
#           The default value to return in the event the preference has
#           no setting
#  @return  The value of the preference, or undefined if there was no
#           user or default value.
 */
function getPref(func, preference, defaultValue) {
  try {
    return Services.prefs[func](preference);
  }
  catch (e) {
  }
  return defaultValue;
}

/**
 * Convert a string containing binary values to hex.
 */
function binaryToHex(input) {
  var result = "";
  for (var i = 0; i < input.length; ++i) {
    var hex = input.charCodeAt(i).toString(16);
    if (hex.length == 1)
      hex = "0" + hex;
    result += hex;
  }
  return result;
}

/**
#  Gets the specified directory at the specified hierarchy under the
#  update root directory and creates it if it doesn't exist.
#  @param   pathArray
#           An array of path components to locate beneath the directory
#           specified by |key|
#  @return  nsIFile object for the location specified.
 */
function getUpdateDirCreate(pathArray) {
  return FileUtils.getDir(KEY_UPDROOT, pathArray, true);
}

/**
#  Gets the specified directory at the specified hierarchy under the
#  update root directory and without creating it if it doesn't exist.
#  @param   pathArray
#           An array of path components to locate beneath the directory
#           specified by |key|
#  @return  nsIFile object for the location specified.
 */
function getUpdateDirNoCreate(pathArray) {
  return FileUtils.getDir(KEY_UPDROOT, pathArray, false);
}

/**
 * Gets the application base directory.
 *
 * @return  nsIFile object for the application base directory.
 */
function getAppBaseDir() {
  return Services.dirsvc.get(KEY_EXECUTABLE, Ci.nsIFile).parent;
}

/**
 * Gets the root of the installation directory which is the application
 * bundle directory on Mac OS X and the location of the application binary
 * on all other platforms.
 *
 * @return nsIFile object for the directory
 */
function getInstallDirRoot() {
  var dir = getAppBaseDir();
#ifdef XP_MACOSX
  // On Mac, we store the Updated.app directory inside the bundle directory.
  dir = dir.parent.parent;
#endif
  return dir;
}

/**
 * Gets the file at the specified hierarchy under the update root directory.
 * @param   pathArray
 *          An array of path components to locate beneath the directory
 *          specified by |key|. The last item in this array must be the
 *          leaf name of a file.
 * @return  nsIFile object for the file specified. The file is NOT created
 *          if it does not exist, however all required directories along
 *          the way are.
 */
function getUpdateFile(pathArray) {
  var file = getUpdateDirCreate(pathArray.slice(0, -1));
  file.append(pathArray[pathArray.length - 1]);
  return file;
}

/**
 * Returns human readable status text from the updates.properties bundle
 * based on an error code
 * @param   code
 *          The error code to look up human readable status text for
 * @param   defaultCode
 *          The default code to look up should human readable status text
 *          not exist for |code|
 * @return  A human readable status text string
 */
function getStatusTextFromCode(code, defaultCode) {
  var reason;
  try {
    reason = gUpdateBundle.GetStringFromName("check_error-" + code);
    LOG("getStatusTextFromCode - transfer error: " + reason + ", code: " +
        code);
  }
  catch (e) {
    // Use the default reason
    reason = gUpdateBundle.GetStringFromName("check_error-" + defaultCode);
    LOG("getStatusTextFromCode - transfer error: " + reason +
        ", default code: " + defaultCode);
  }
  return reason;
}

/**
 * Record count in the health report.
 * @param field
 *        The field name to record
 * @param status
 *        Status code for errors, 0 otherwise
 */
function recordInHealthReport(field, status) {
#ifdef MOZ_SERVICES_HEALTHREPORT
  try {
    LOG("recordInHealthReport - " + field + " - " + status);

    let reporter = Cc["@mozilla.org/datareporting/service;1"]
                      .getService().wrappedJSObject.healthReporter;

    if (reporter) {
      reporter.onInit().then(function recordUpdateInHealthReport() {
        try {
          reporter.getProvider("org.mozilla.update").recordUpdate(field, status);
        } catch (ex) {
          Cu.reportError(ex);
        }
      });
    }
  // If getting the heath reporter service fails, don't fail updating.
  } catch (ex) {
    LOG("recordInHealthReport - could not initialize health reporter");
  }
#endif
}

/**
 * Get the Active Updates directory
 * @return The active updates directory, as a nsIFile object
 */
function getUpdatesDir() {
  // Right now, we only support downloading one patch at a time, so we always
  // use the same target directory.
  return getUpdateDirCreate([DIR_UPDATES, "0"]);
}

/**
 * Get the Active Updates directory inside the directory where we apply the
 * staged update.
 * @return The active updates directory inside the updated directory, as a
 *         nsIFile object.
 */
function getUpdatesDirInApplyToDir() {
  var dir = getAppBaseDir();
#ifdef XP_MACOSX
  dir = dir.parent.parent; // the bundle directory
#endif
  dir.append(UPDATED_DIR);
#ifdef XP_MACOSX
  dir.append("Contents");
  dir.append("MacOS");
#endif
  dir.append(DIR_UPDATES);
  if (!dir.exists()) {
    dir.create(Ci.nsILocalFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
  }
  return dir;
}

/**
 * Reads the update state from the update.status file in the specified
 * directory.
 * @param   dir
 *          The dir to look for an update.status file in
 * @return  The status value of the update.
 */
function readStatusFile(dir) {
  var statusFile = dir.clone();
  statusFile.append(FILE_UPDATE_STATUS);
  var status = readStringFromFile(statusFile) || STATE_NONE;
  LOG("readStatusFile - status: " + status + ", path: " + statusFile.path);
  return status;
}

/**
 * Writes the current update operation/state to a file in the patch
 * directory, indicating to the patching system that operations need
 * to be performed.
 * @param   dir
 *          The patch directory where the update.status file should be
 *          written.
 * @param   state
 *          The state value to write.
 */
function writeStatusFile(dir, state) {
  var statusFile = dir.clone();
  statusFile.append(FILE_UPDATE_STATUS);
  writeStringToFile(statusFile, state);
}

#ifdef MOZ_WIDGET_GONK
/**
 * Reads the link file specified in the update.link file in the
 * specified directory and returns the nsIFile for the
 * corresponding file.
 * @param   dir
 *          The dir to look for an update.link file in
 * @return  A nsIFile for the file path specified in the
 *          update.link file or null if the update.link file
 *          doesn't exist.
 */
function getFileFromUpdateLink(dir) {
  var linkFile = dir.clone();
  linkFile.append(FILE_UPDATE_LINK);
  var link = readStringFromFile(linkFile);
  LOG("getFileFromUpdateLink linkFile.path: " + linkFile.path + ", link: " + link);
  if (!link) {
    return null;
  }
  let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
  file.initWithPath(link);
  return file;
}

/**
 * Creates a link file, which allows the actual patch to live in
 * a directory different from the update directory.
 * @param   dir
 *          The patch directory where the update.link file
 *          should be written.
 * @param   patchFile
 *          The fully qualified filename of the patchfile.
 */
function writeLinkFile(dir, patchFile) {
  var linkFile = dir.clone();
  linkFile.append(FILE_UPDATE_LINK);
  writeStringToFile(linkFile, patchFile.path);
  if (patchFile.path.indexOf(gExtStorage) == 0) {
    // The patchfile is being stored on external storage. Try to lock it
    // so that it doesn't get shared with the PC while we're downloading
    // to it.
    acquireSDCardMountLock();
  }
}

/**
 * Acquires a VolumeMountLock for the sdcard volume.
 *
 * This prevents the SDCard from being shared with the PC while
 * we're downloading the update.
 */
function acquireSDCardMountLock() {
  let volsvc = Cc["@mozilla.org/telephony/volume-service;1"].
                    getService(Ci.nsIVolumeService);
  if (volsvc) {
    gSDCardMountLock = volsvc.createMountLock("sdcard");
  }
}

/**
 * Determines if the state corresponds to an interrupted update.
 * This could either be because the download was interrupted, or
 * because staging the update was interrupted.
 *
 * @return true if the state corresponds to an interrupted
 *         update.
 */
function isInterruptedUpdate(status) {
  return (status == STATE_DOWNLOADING) ||
         (status == STATE_PENDING) ||
         (status == STATE_APPLYING);
}
#endif // MOZ_WIDGET_GONK

/**
 * Releases any SDCard mount lock that we might have.
 *
 * This once again allows the SDCard to be shared with the PC.
 *
 * This function was placed outside the #ifdef so that we didn't
 * need to put #ifdefs around the callers.
 */
function releaseSDCardMountLock() {
#ifdef MOZ_WIDGET_GONK
  if (gSDCardMountLock) {
    gSDCardMountLock.unlock();
    gSDCardMountLock = null;
  }
#endif
}

/**
#  Writes the update's application version to a file in the patch directory. If
#  the update doesn't provide application version information via the
#  appVersion attribute the string "null" will be written to the file.
#  This value is compared during startup (in nsUpdateDriver.cpp) to determine if
#  the update should be applied. Note that this won't provide protection from
#  downgrade of the application for the nightly user case where the application
#  version doesn't change.
#  @param   dir
#           The patch directory where the update.version file should be
#           written.
#  @param   version
#           The version value to write. Will be the string "null" when the
#           update doesn't provide the appVersion attribute in the update xml.
 */
function writeVersionFile(dir, version) {
  var versionFile = dir.clone();
  versionFile.append(FILE_UPDATE_VERSION);
  writeStringToFile(versionFile, version);
}

/**
 * Removes the MozUpdater directory that is created when replacing an install
 * with a staged update and leftover MozUpdater-i folders in the tmp directory.
 */
function cleanUpMozUpdaterDirs() {
  try {
    // Remove the MozUpdater directory in the updates/0 directory.
    var mozUpdaterDir = getUpdatesDir();
    mozUpdaterDir.append("MozUpdater");
    if (mozUpdaterDir.exists()) {
      LOG("cleanUpMozUpdaterDirs - removing MozUpdater directory");
      mozUpdaterDir.remove(true);
    }
  } catch (e) {
    LOG("cleanUpMozUpdaterDirs - Exception: " + e);
  }

  try {
    var tmpDir = Cc["@mozilla.org/file/directory_service;1"].
                 getService(Ci.nsIProperties).
                 get("TmpD", Ci.nsIFile);

    // We used to store MozUpdater-i directories in the temp directory.
    // We need to remove these directories if we detect that they still exist.
    // To check if they still exist, we simply check for MozUpdater-1.
    var mozUpdaterDir1 = tmpDir.clone();
    mozUpdaterDir1.append("MozUpdater-1");
    // Only try to delete the left over directories in "$Temp/MozUpdater-i/*" if
    // MozUpdater-1 exists.
    if (mozUpdaterDir1.exists()) {
      LOG("cleanUpMozUpdaterDirs - Removing top level tmp MozUpdater-i " +
          "directories");
      let i = 0;
      let dirEntries = tmpDir.directoryEntries;
      while (dirEntries.hasMoreElements() && i < 10) {
        let file = dirEntries.getNext().QueryInterface(Ci.nsILocalFile);
        if (file.leafName.startsWith("MozUpdater-") && file.leafName != "MozUpdater-1") {
          file.remove(true);
          i++;
        }
      }
      // If you enumerate the whole temp directory and the count of deleted
      // items is less than 10, then delete MozUpdate-1.
      if (i < 10) {
        mozUpdaterDir1.remove(true);
      }
    }
  } catch (e) {
    LOG("cleanUpMozUpdaterDirs - Exception: " + e);
  }
}

/**
 * Removes the contents of the Updates Directory
 *
 * @param aBackgroundUpdate Whether the update has been performed in the
 *        background.  If this is true, we move the update log file to the
 *        updated directory, so that it survives replacing the directories
 *        later on.
 */
function cleanUpUpdatesDir(aBackgroundUpdate) {
  // Bail out if we don't have appropriate permissions
  try {
    var updateDir = getUpdatesDir();
  } catch (e) {
    return;
  }

  // Preserve the last update log file for debugging purposes.
  let file = updateDir.clone();
  file.append(FILE_UPDATE_LOG);
  if (file.exists()) {
    let dir;
    if (aBackgroundUpdate && getUpdateDirNoCreate([]).equals(getAppBaseDir())) {
      dir = getUpdatesDirInApplyToDir();
    } else {
      dir = updateDir.parent;
    }
    let logFile = dir.clone();
    logFile.append(FILE_LAST_LOG);
    if (logFile.exists()) {
      try {
        logFile.moveTo(dir, FILE_BACKUP_LOG);
      } catch (e) {
        LOG("cleanUpUpdatesDir - failed to rename file " + logFile.path +
            " to " + FILE_BACKUP_LOG);
      }
    }

    try {
      file.moveTo(dir, FILE_LAST_LOG);
    } catch (e) {
      LOG("cleanUpUpdatesDir - failed to rename file " + file.path +
          " to " + FILE_LAST_LOG);
    }
  }

  if (!aBackgroundUpdate) {
    let e = updateDir.directoryEntries;
    while (e.hasMoreElements()) {
      let f = e.getNext().QueryInterface(Ci.nsIFile);
#ifdef MOZ_WIDGET_GONK
      if (f.leafName == FILE_UPDATE_LINK) {
        let linkedFile = getFileFromUpdateLink(updateDir);
        if (linkedFile && linkedFile.exists()) {
          linkedFile.remove(false);
        }
      }
#endif

      // Now, recursively remove this file.  The recursive removal is needed for
      // Mac OSX because this directory will contain a copy of updater.app,
      // which is itself a directory.
      try {
        f.remove(true);
      } catch (e) {
        LOG("cleanUpUpdatesDir - failed to remove file " + f.path);
      }
    }
  }
  releaseSDCardMountLock();
}

/**
 * Clean up updates list and the updates directory.
 */
function cleanupActiveUpdate() {
  // Move the update from the Active Update list into the Past Updates list.
  var um = Cc["@mozilla.org/updates/update-manager;1"].
           getService(Ci.nsIUpdateManager);
  um.activeUpdate = null;
  um.saveUpdates();

  // Now trash the updates directory, since we're done with it
  cleanUpUpdatesDir();
}

/**
 * Gets the locale from the update.locale file for replacing %LOCALE% in the
 * update url. The update.locale file can be located in the application
 * directory or the GRE directory with preference given to it being located in
 * the application directory.
 */
function getLocale() {
  if (gLocale)
    return gLocale;

  for (let res of ['app', 'gre']) {
    var channel = Services.io.newChannel2("resource://" + res + "/" + FILE_UPDATE_LOCALE,
                                          null,
                                          null,
                                          null,      // aLoadingNode
                                          Services.scriptSecurityManager.getSystemPrincipal(),
                                          null,      // aTriggeringPrincipal
                                          Ci.nsILoadInfo.SEC_NORMAL,
                                          Ci.nsIContentPolicy.TYPE_DATAREQUEST);
    try {
      var inputStream = channel.open();
      gLocale = readStringFromInputStream(inputStream);
    } catch(e) {}
    if (gLocale)
      break;
  }

  if (!gLocale)
    throw Components.Exception(FILE_UPDATE_LOCALE + " file doesn't exist in " +
                               "either the application or GRE directories",
                               Cr.NS_ERROR_FILE_NOT_FOUND);

  LOG("getLocale - getting locale from file: " + channel.originalURI.spec +
      ", locale: " + gLocale);
  return gLocale;
}

/* Get the distribution pref values, from defaults only */
function getDistributionPrefValue(aPrefName) {
  var prefValue = "default";

  try {
    prefValue = Services.prefs.getDefaultBranch(null).getCharPref(aPrefName);
  } catch (e) {
    // use default when pref not found
  }

  return prefValue;
}

/**
 * An enumeration of items in a JS array.
 * @constructor
 */
function ArrayEnumerator(aItems) {
  this._index = 0;
  if (aItems) {
    for (var i = 0; i < aItems.length; ++i) {
      if (!aItems[i])
        aItems.splice(i, 1);
    }
  }
  this._contents = aItems;
}

ArrayEnumerator.prototype = {
  _index: 0,
  _contents: [],

  hasMoreElements: function ArrayEnumerator_hasMoreElements() {
    return this._index < this._contents.length;
  },

  getNext: function ArrayEnumerator_getNext() {
    return this._contents[this._index++];
  }
};

/**
 * Writes a string of text to a file.  A newline will be appended to the data
 * written to the file.  This function only works with ASCII text.
 */
function writeStringToFile(file, text) {
  var fos = FileUtils.openSafeFileOutputStream(file)
  text += "\n";
  fos.write(text, text.length);
  FileUtils.closeSafeFileOutputStream(fos);
}

function readStringFromInputStream(inputStream) {
  var sis = Cc["@mozilla.org/scriptableinputstream;1"].
            createInstance(Ci.nsIScriptableInputStream);
  sis.init(inputStream);
  var text = sis.read(sis.available());
  sis.close();
  if (text[text.length - 1] == "\n")
    text = text.slice(0, -1);
  return text;
}

/**
 * Reads a string of text from a file.  A trailing newline will be removed
 * before the result is returned.  This function only works with ASCII text.
 */
function readStringFromFile(file) {
  if (!file.exists()) {
    LOG("readStringFromFile - file doesn't exist: " + file.path);
    return null;
  }
  var fis = Cc["@mozilla.org/network/file-input-stream;1"].
            createInstance(Ci.nsIFileInputStream);
  fis.init(file, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0);
  return readStringFromInputStream(fis);
}

function handleUpdateFailure(update, errorCode) {
  update.errorCode = parseInt(errorCode);
  if (update.errorCode == FOTA_GENERAL_ERROR ||
      update.errorCode == FOTA_FILE_OPERATION_ERROR ||
      update.errorCode == FOTA_RECOVERY_ERROR ||
      update.errorCode == FOTA_UNKNOWN_ERROR) {
    // In the case of FOTA update errors, don't reset the state to pending. This
    // causes the FOTA update path to try again, which is not necessarily what
    // we want.
    update.statusText = gUpdateBundle.GetStringFromName("statusFailed");

    Cc["@mozilla.org/updates/update-prompt;1"].
      createInstance(Ci.nsIUpdatePrompt).
      showUpdateError(update);
    writeStatusFile(getUpdatesDir(), STATE_FAILED + ": " + errorCode);
    cleanupActiveUpdate();
    return true;
  }

  if (update.errorCode == WRITE_ERROR ||
      update.errorCode == WRITE_ERROR_ACCESS_DENIED ||
      update.errorCode == WRITE_ERROR_SHARING_VIOLATION_SIGNALED ||
      update.errorCode == WRITE_ERROR_SHARING_VIOLATION_NOPROCESSFORPID ||
      update.errorCode == WRITE_ERROR_SHARING_VIOLATION_NOPID ||
      update.errorCode == WRITE_ERROR_CALLBACK_APP ||
      update.errorCode == FILESYSTEM_MOUNT_READWRITE_ERROR) {
    Cc["@mozilla.org/updates/update-prompt;1"].
      createInstance(Ci.nsIUpdatePrompt).
      showUpdateError(update);
    writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
    return true;
  }

  if (update.errorCode == ELEVATION_CANCELED) {
    writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
    return true;
  }

  return false;
}

/**
 * Fall back to downloading a complete update in case an update has failed.
 *
 * @param update the update object that has failed to apply.
 * @param postStaging true if we have just attempted to stage an update.
 */
function handleFallbackToCompleteUpdate(update, postStaging) {
  cleanupActiveUpdate();

  update.statusText = gUpdateBundle.GetStringFromName("patchApplyFailure");
  var oldType = update.selectedPatch ? update.selectedPatch.type
                                     : "complete";
  if (update.selectedPatch && oldType == "partial" && update.patchCount == 2) {
    // Partial patch application failed, try downloading the complete
    // update in the background instead.
    LOG("handleFallbackToCompleteUpdate - install of partial patch " +
        "failed, downloading complete patch");
    var status = Cc["@mozilla.org/updates/update-service;1"].
                 getService(Ci.nsIApplicationUpdateService).
                 downloadUpdate(update, !postStaging);
    if (status == STATE_NONE)
      cleanupActiveUpdate();
  }
  else {
    LOG("handleFallbackToCompleteUpdate - install of complete or " +
        "only one patch offered failed.");
  }
  update.QueryInterface(Ci.nsIWritablePropertyBag);
  update.setProperty("patchingFailed", oldType);
}

/**
 * Update Patch
 * @param   patch
 *          A <patch> element to initialize this object with
 * @throws if patch has a size of 0
 * @constructor
 */
function UpdatePatch(patch) {
  this._properties = {};
  for (var i = 0; i < patch.attributes.length; ++i) {
    var attr = patch.attributes.item(i);
    attr.QueryInterface(Ci.nsIDOMAttr);
    switch (attr.name) {
    case "selected":
      this.selected = attr.value == "true";
      break;
    case "size":
      if (0 == parseInt(attr.value)) {
        LOG("UpdatePatch:init - 0-sized patch!");
        throw Cr.NS_ERROR_ILLEGAL_VALUE;
      }
      // fall through
    default:
      this[attr.name] = attr.value;
      break;
    };
  }
}
UpdatePatch.prototype = {
  /**
   * See nsIUpdateService.idl
   */
  serialize: function UpdatePatch_serialize(updates) {
    var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
    patch.setAttribute("type", this.type);
    patch.setAttribute("URL", this.URL);
    // finalURL is not available until after the download has started
    if (this.finalURL)
      patch.setAttribute("finalURL", this.finalURL);
    patch.setAttribute("hashFunction", this.hashFunction);
    patch.setAttribute("hashValue", this.hashValue);
    patch.setAttribute("size", this.size);
    patch.setAttribute("selected", this.selected);
    patch.setAttribute("state", this.state);

    for (var p in this._properties) {
      if (this._properties[p].present)
        patch.setAttribute(p, this._properties[p].data);
    }

    return patch;
  },

  /**
   * A hash of custom properties
   */
  _properties: null,

  /**
   * See nsIWritablePropertyBag.idl
   */
  setProperty: function UpdatePatch_setProperty(name, value) {
    this._properties[name] = { data: value, present: true };
  },

  /**
   * See nsIWritablePropertyBag.idl
   */
  deleteProperty: function UpdatePatch_deleteProperty(name) {
    if (name in this._properties)
      this._properties[name].present = false;
    else
      throw Cr.NS_ERROR_FAILURE;
  },

  /**
   * See nsIPropertyBag.idl
   */
  get enumerator() {
    var properties = [];
    for (var p in this._properties)
      properties.push(this._properties[p].data);
    return new ArrayEnumerator(properties);
  },

  /**
   * See nsIPropertyBag.idl
   */
  getProperty: function UpdatePatch_getProperty(name) {
    if (name in this._properties &&
        this._properties[name].present)
      return this._properties[name].data;
    throw Cr.NS_ERROR_FAILURE;
  },

  /**
   * Returns whether or not the update.status file for this patch exists at the
   * appropriate location.
   */
  get statusFileExists() {
    var statusFile = getUpdatesDir();
    statusFile.append(FILE_UPDATE_STATUS);
    return statusFile.exists();
  },

  /**
   * See nsIUpdateService.idl
   */
  get state() {
    if (this._properties.state)
      return this._properties.state;
    return STATE_NONE;
  },
  set state(val) {
    this._properties.state = val;
  },

  QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdatePatch,
                                         Ci.nsIPropertyBag,
                                         Ci.nsIWritablePropertyBag])
};

/**
 * Update
 * Implements nsIUpdate
 * @param   update
 *          An <update> element to initialize this object with
 * @throws if the update contains no patches
 * @constructor
 */
function Update(update) {
  this._properties = {};
  this._patches = [];
  this.isCompleteUpdate = false;
  this.isOSUpdate = false;
  this.showPrompt = false;
  this.showNeverForVersion = false;
  this.unsupported = false;
  this.channel = "default";
  this.promptWaitTime = getPref("getIntPref", PREF_APP_UPDATE_PROMPTWAITTIME, 43200);

  // Null <update>, assume this is a message container and do no
  // further initialization
  if (!update)
    return;

  const ELEMENT_NODE = Ci.nsIDOMNode.ELEMENT_NODE;
  for (var i = 0; i < update.childNodes.length; ++i) {
    var patchElement = update.childNodes.item(i);
    if (patchElement.nodeType != ELEMENT_NODE ||
        patchElement.localName != "patch")
      continue;

    patchElement.QueryInterface(Ci.nsIDOMElement);
    try {
      var patch = new UpdatePatch(patchElement);
    } catch (e) {
      continue;
    }
    this._patches.push(patch);
  }

  if (this._patches.length == 0 && !update.hasAttribute("unsupported"))
    throw Cr.NS_ERROR_ILLEGAL_VALUE;

  // Fallback to the behavior prior to bug 530872 if the update does not have an
  // appVersion attribute.
  if (!update.hasAttribute("appVersion")) {
    if (update.getAttribute("type") == "major") {
      if (update.hasAttribute("detailsURL")) {
        this.billboardURL = update.getAttribute("detailsURL");
        this.showPrompt = true;
        this.showNeverForVersion = true;
      }
    }
  }

  for (var i = 0; i < update.attributes.length; ++i) {
    var attr = update.attributes.item(i);
    attr.QueryInterface(Ci.nsIDOMAttr);
    if (attr.value == "undefined")
      continue;
    else if (attr.name == "detailsURL")
      this._detailsURL = attr.value;
    else if (attr.name == "extensionVersion") {
      // Prevent extensionVersion from replacing appVersion if appVersion is
      // present in the update xml.
      if (!this.appVersion)
        this.appVersion = attr.value;
    }
    else if (attr.name == "installDate" && attr.value)
      this.installDate = parseInt(attr.value);
    else if (attr.name == "isCompleteUpdate")
      this.isCompleteUpdate = attr.value == "true";
    else if (attr.name == "isSecurityUpdate")
      this.isSecurityUpdate = attr.value == "true";
    else if (attr.name == "isOSUpdate")
      this.isOSUpdate = attr.value == "true";
    else if (attr.name == "showNeverForVersion")
      this.showNeverForVersion = attr.value == "true";
    else if (attr.name == "showPrompt")
      this.showPrompt = attr.value == "true";
    else if (attr.name == "promptWaitTime")
    {
      if(!isNaN(attr.value))
        this.promptWaitTime = parseInt(attr.value);
    }
    else if (attr.name == "unsupported")
      this.unsupported = attr.value == "true";
    else if (attr.name == "version") {
      // Prevent version from replacing displayVersion if displayVersion is
      // present in the update xml.
      if (!this.displayVersion)
        this.displayVersion = attr.value;
    }
    else {
      this[attr.name] = attr.value;

      switch (attr.name) {
      case "appVersion":
      case "billboardURL":
      case "buildID":
      case "channel":
      case "displayVersion":
      case "licenseURL":
      case "name":
      case "platformVersion":
      case "previousAppVersion":
      case "serviceURL":
      case "statusText":
      case "type":
        break;
      default:
        // Save custom attributes when serializing to the local xml file but
        // don't use this method for the expected attributes which are already
        // handled in serialize.
        this.setProperty(attr.name, attr.value);
        break;
      };
    }
  }

  // Set the initial value with the current time when it doesn't already have a
  // value or the value is already set to 0 (bug 316328).
  if (!this.installDate && this.installDate != 0)
    this.installDate = (new Date()).getTime();

  // The Update Name is either the string provided by the <update> element, or
  // the string: "<App Name> <Update App Version>"
  var name = "";
  if (update.hasAttribute("name"))
    name = update.getAttribute("name");
  else {
    var brandBundle = Services.strings.createBundle(URI_BRAND_PROPERTIES);
    var appName = brandBundle.GetStringFromName("brandShortName");
    name = gUpdateBundle.formatStringFromName("updateName",
                                              [appName, this.displayVersion], 2);
  }
  this.name = name;
}
Update.prototype = {
  /**
   * See nsIUpdateService.idl
   */
  get patchCount() {
    return this._patches.length;
  },

  /**
   * See nsIUpdateService.idl
   */
  getPatchAt: function Update_getPatchAt(index) {
    return this._patches[index];
  },

  /**
   * See nsIUpdateService.idl
   *
   * We use a copy of the state cached on this object in |_state| only when
   * there is no selected patch, i.e. in the case when we could not load
   * |.activeUpdate| from the update manager for some reason but still have
   * the update.status file to work with.
   */
  _state: "",
  set state(state) {
    if (this.selectedPatch)
      this.selectedPatch.state = state;
    this._state = state;
    return state;
  },
  get state() {
    if (this.selectedPatch)
      return this.selectedPatch.state;
    return this._state;
  },

  /**
   * See nsIUpdateService.idl
   */
  errorCode: 0,

  /**
   * See nsIUpdateService.idl
   */
  get selectedPatch() {
    for (var i = 0; i < this.patchCount; ++i) {
      if (this._patches[i].selected)
        return this._patches[i];
    }
    return null;
  },

  /**
   * See nsIUpdateService.idl
   */
  get detailsURL() {
    if (!this._detailsURL) {
      try {
        // Try using a default details URL supplied by the distribution
        // if the update XML does not supply one.
        return Services.urlFormatter.formatURLPref(PREF_APP_UPDATE_URL_DETAILS);
      }
      catch (e) {
      }
    }
    return this._detailsURL || "";
  },

  /**
   * See nsIUpdateService.idl
   */
  serialize: function Update_serialize(updates) {
    var update = updates.createElementNS(URI_UPDATE_NS, "update");
    update.setAttribute("appVersion", this.appVersion);
    update.setAttribute("buildID", this.buildID);
    update.setAttribute("channel", this.channel);
    update.setAttribute("displayVersion", this.displayVersion);
    // for backwards compatibility in case the user downgrades
    update.setAttribute("extensionVersion", this.appVersion);
    update.setAttribute("installDate", this.installDate);
    update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
    update.setAttribute("isOSUpdate", this.isOSUpdate);
    update.setAttribute("name", this.name);
    update.setAttribute("serviceURL", this.serviceURL);
    update.setAttribute("showNeverForVersion", this.showNeverForVersion);
    update.setAttribute("showPrompt", this.showPrompt);
    update.setAttribute("promptWaitTime", this.promptWaitTime);
    update.setAttribute("type", this.type);
    // for backwards compatibility in case the user downgrades
    update.setAttribute("version", this.displayVersion);

    // Optional attributes
    if (this.billboardURL)
      update.setAttribute("billboardURL", this.billboardURL);
    if (this.detailsURL)
      update.setAttribute("detailsURL", this.detailsURL);
    if (this.licenseURL)
      update.setAttribute("licenseURL", this.licenseURL);
    if (this.platformVersion)
      update.setAttribute("platformVersion", this.platformVersion);
    if (this.previousAppVersion)
      update.setAttribute("previousAppVersion", this.previousAppVersion);
    if (this.statusText)
      update.setAttribute("statusText", this.statusText);
    if (this.unsupported)
      update.setAttribute("unsupported", this.unsupported);
    updates.documentElement.appendChild(update);

    for (var p in this._properties) {
      if (this._properties[p].present)
        update.setAttribute(p, this._properties[p].data);
    }

    for (var i = 0; i < this.patchCount; ++i)
      update.appendChild(this.getPatchAt(i).serialize(updates));

    return update;
  },

  /**
   * A hash of custom properties
   */
  _properties: null,

  /**
   * See nsIWritablePropertyBag.idl
   */
  setProperty: function Update_setProperty(name, value) {
    this._properties[name] = { data: value, present: true };
  },

  /**
   * See nsIWritablePropertyBag.idl
   */
  deleteProperty: function Update_deleteProperty(name) {
    if (name in this._properties)
      this._properties[name].present = false;
    else
      throw Cr.NS_ERROR_FAILURE;
  },

  /**
   * See nsIPropertyBag.idl
   */
  get enumerator() {
    var properties = [];
    for (var p in this._properties)
      properties.push(this._properties[p].data);
    return new ArrayEnumerator(properties);
  },

  /**
   * See nsIPropertyBag.idl
   */
  getProperty: function Update_getProperty(name) {
    if (name in this._properties && this._properties[name].present)
      return this._properties[name].data;
    throw Cr.NS_ERROR_FAILURE;
  },

  QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdate,
                                         Ci.nsIPropertyBag,
                                         Ci.nsIWritablePropertyBag])
};

const UpdateServiceFactory = {
  _instance: null,
  createInstance: function (outer, iid) {
    if (outer != null)
      throw Cr.NS_ERROR_NO_AGGREGATION;
    return this._instance == null ? this._instance = new UpdateService() :
                                    this._instance;
  }
};

/**
 * UpdateService
 * A Service for managing the discovery and installation of software updates.
 * @constructor
 */
function UpdateService() {
  LOG("Creating UpdateService");
  Services.obs.addObserver(this, "xpcom-shutdown", false);
  Services.prefs.addObserver(PREF_APP_UPDATE_LOG, this, false);
#ifdef MOZ_WIDGET_GONK
  // PowerManagerService::SyncProfile (which is called for Reboot, PowerOff
  // and Restart) sends the profile-change-net-teardown event. We can then
  // pause the download in a similar manner to xpcom-shutdown.
  Services.obs.addObserver(this, "profile-change-net-teardown", false);
#endif
}

UpdateService.prototype = {
  /**
   * The downloader we are using to download updates. There is only ever one of
   * these.
   */
  _downloader: null,

  /**
   * Incompatible add-on count.
   */
  _incompatAddonsCount: 0,

  /**
   * Whether or not the service registered the "online" observer.
   */
  _registeredOnlineObserver: false,

  /**
   * The current number of consecutive socket errors
   */
  _consecutiveSocketErrors: 0,

  /**
   * A timer used to retry socket errors
   */
  _retryTimer: null,

  /**
   * Whether or not a background update check was initiated by the
   * application update timer notification.
   */
  _isNotify: true,

  /**
   * Handle Observer Service notifications
   * @param   subject
   *          The subject of the notification
   * @param   topic
   *          The notification name
   * @param   data
   *          Additional data
   */
  observe: function AUS_observe(subject, topic, data) {
    switch (topic) {
    case "post-update-processing":
      // Clean up any extant updates
      this._postUpdateProcessing();
      break;
    case "network:offline-status-changed":
      this._offlineStatusChanged(data);
      break;
    case "nsPref:changed":
      if (data == PREF_APP_UPDATE_LOG) {
        gLogEnabled = getPref("getBoolPref", PREF_APP_UPDATE_LOG, false);
      }
      break;
#ifdef MOZ_WIDGET_GONK
    case "profile-change-net-teardown": // fall thru
#endif
    case "xpcom-shutdown":
      Services.obs.removeObserver(this, topic);
      Services.prefs.removeObserver(PREF_APP_UPDATE_LOG, this);

#ifdef XP_WIN
      // If we hold the update mutex, let it go!
      // The OS would clean this up sometime after shutdown,
      // but that would have no guarantee on timing.
      if (gUpdateMutexHandle) {
        closeHandle(gUpdateMutexHandle);
      }
#endif
      if (this._retryTimer) {
        this._retryTimer.cancel();
      }

      this.pauseDownload();
      // Prevent leaking the downloader (bug 454964)
      this._downloader = null;
      break;
    }
  },

  /**
   * The following needs to happen during the post-update-processing
   * notification from nsUpdateServiceStub.js:
   * 1. post update processing
   * 2. resume of a download that was in progress during a previous session
   * 3. start of a complete update download after the failure to apply a partial
   *    update
   */

  /**
   * Perform post-processing on updates lingering in the updates directory
   * from a previous application session - either report install failures (and
   * optionally attempt to fetch a different version if appropriate) or
   * notify the user of install success.
   */
  _postUpdateProcessing: function AUS__postUpdateProcessing() {
    // canCheckForUpdates will return false when metro-only updates are disabled
    // from within metro.  In that case we still want _postUpdateProcessing to
    // run.  gMetroUpdatesEnabled returns true on non Windows 8 platforms.
    // We want _postUpdateProcessing to run so that it will update the history
    // XML. Without updating the history XML, the about flyout will continue to
    // have the "Restart to Apply Update" button (history xml indicates update
    // is applied).
    // TODO: I think this whole if-block should be removed since updates can
    // always be applied via the about dialog, we should be running post update
    // in those cases.
    if (!this.canCheckForUpdates && gMetroUpdatesEnabled) {
      LOG("UpdateService:_postUpdateProcessing - unable to check for " +
          "updates... returning early");
      return;
    }

    if (!this.canApplyUpdates) {
      LOG("UpdateService:_postUpdateProcessing - unable to apply " +
          "updates... returning early");
      // If the update is present in the update directly somehow,
      // it would prevent us from notifying the user of futher updates.
      cleanupActiveUpdate();
      return;
    }

    var status = readStatusFile(getUpdatesDir());
    // STATE_NONE status means that the update.status file is present but a
    // background download error occurred.
    if (status == STATE_NONE) {
      LOG("UpdateService:_postUpdateProcessing - no status, no update");
      cleanupActiveUpdate();
      return;
    }

    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);

#ifdef MOZ_WIDGET_GONK
    // This code is called very early in the boot process, before we've even
    // had a chance to setup the UI so we can give feedback to the user.
    //
    // Since the download may be occuring over a link which has associated
    // cost, we want to require user-consent before resuming the download.
    // Also, applying an already downloaded update now is undesireable,
    // since the phone will look dead while the update is being applied.
    // Applying the update can take several minutes. Instead we wait until
    // the UI is initialized so it is possible to give feedback to and get
    // consent to update from the user.
    if (isInterruptedUpdate(status)) {
      LOG("UpdateService:_postUpdateProcessing - interrupted update detected - wait for user consent");
      return;
    }
#endif

    var update = um.activeUpdate;

    if (status == STATE_DOWNLOADING) {
      LOG("UpdateService:_postUpdateProcessing - patch found in downloading " +
          "state");
      if (update && update.state != STATE_SUCCEEDED) {
        // Resume download
        var status = this.downloadUpdate(update, true);
        if (status == STATE_NONE)
          cleanupActiveUpdate();
      }
      return;
    }

    if (status == STATE_APPLYING) {
      // This indicates that the background updater service is in either of the
      // following two states:
      // 1. It is in the process of applying an update in the background, and
      //    we just happen to be racing against that.
      // 2. It has failed to apply an update for some reason, and we hit this
      //    case because the updater process has set the update status to
      //    applying, but has never finished.
      // In order to differentiate between these two states, we look at the
      // state field of the update object.  If it's "pending", then we know
      // that this is the first time we're hitting this case, so we switch
      // that state to "applying" and we just wait and hope for the best.
      // If it's "applying", we know that we've already been here once, so
      // we really want to start from a clean state.
      if (update && update.state == STATE_PENDING) {
        LOG("UpdateService:_postUpdateProcessing - patch found in applying " +
            "state for the first time");
        update.state = STATE_APPLYING;
        um.saveUpdates();
      } else { // We get here even if we don't have an update object
        LOG("UpdateService:_postUpdateProcessing - patch found in applying " +
            "state for the second time");
        cleanupActiveUpdate();
      }
      return;
    }

#ifdef MOZ_WIDGET_GONK
    // The update is only applied but not selected to be installed
    if (status == STATE_APPLIED && update && update.isOSUpdate) {
      LOG("UpdateService:_postUpdateProcessing - update staged as applied found");
      return;
    }

    if (status == STATE_APPLIED_OS && update && update.isOSUpdate) {
      // In gonk, we need to check for OS update status after startup, since
      // the recovery partition won't write to update.status for us
      var recoveryService = Cc["@mozilla.org/recovery-service;1"].
                            getService(Ci.nsIRecoveryService);

      var fotaStatus = recoveryService.getFotaUpdateStatus();
      switch (fotaStatus) {
        case Ci.nsIRecoveryService.FOTA_UPDATE_SUCCESS:
          status = STATE_SUCCEEDED;
          break;
        case Ci.nsIRecoveryService.FOTA_UPDATE_FAIL:
          status = STATE_FAILED + ": " + FOTA_GENERAL_ERROR;
          break;
        case Ci.nsIRecoveryService.FOTA_UPDATE_UNKNOWN:
        default:
          status = STATE_FAILED + ": " + FOTA_UNKNOWN_ERROR;
          break;
      }
    }
#endif

    if (!update) {
      if (status != STATE_SUCCEEDED) {
        LOG("UpdateService:_postUpdateProcessing - previous patch failed " +
            "and no patch available");
        cleanupActiveUpdate();
        return;
      }
      update = new Update(null);
    }

    var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                   createInstance(Ci.nsIUpdatePrompt);

    update.state = status;
    this._sendStatusCodeTelemetryPing(status);

    if (status == STATE_SUCCEEDED) {
      update.statusText = gUpdateBundle.GetStringFromName("installSuccess");

      // Update the patch's metadata.
      um.activeUpdate = update;
      Services.prefs.setBoolPref(PREF_APP_UPDATE_POSTUPDATE, true);
      prompter.showUpdateInstalled();

      // Done with this update. Clean it up.
      cleanupActiveUpdate();
    }
    else {
      // If we hit an error, then the error code will be included in the status
      // string following a colon and a space. If we had an I/O error, then we
      // assume that the patch is not invalid, and we re-stage the patch so that
      // it can be attempted again the next time we restart. This will leave a
      // space at the beginning of the error code when there is a failure which
      // will be removed by using parseInt below. This prevents panic which has
      // occurred numerous times previously (see bug 569642 comment #9 for one
      // example) when testing releases due to forgetting to include the space.
      var ary = status.split(":");
      update.state = ary[0];
      if (update.state == STATE_FAILED && ary[1]) {
        if (handleUpdateFailure(update, ary[1])) {
          return;
        }
      }

      // Something went wrong with the patch application process.
      handleFallbackToCompleteUpdate(update, false);

      prompter.showUpdateError(update);
    }

    // Now trash the MozUpdater directory created when replacing an install with
    // a staged update.
    cleanUpMozUpdaterDirs();
  },

  /**
   * Submit a telemetry ping with the boolean value of a pref for a histogram
   *
   * @param  pref
   *         The preference to report
   * @param  histogram
   *         The histogram ID to report to
   */
  _sendBoolPrefTelemetryPing: function AUS__boolTelemetryPing(pref, histogram) {
    try {
      // The getPref is already wrapped in a try/catch but we never
      // want telemetry pings breaking app update so we just put it
      // inside the try to be safe.
      let val = getPref("getBoolPref", pref, false);
      Services.telemetry.getHistogramById(histogram).add(+val);
    } catch(e) {
      // Don't allow any exception to be propagated.
      Cu.reportError(e);
    }
  },

  /**
   * Submit a telemetry ping with the int value of a pref for a histogram
   *
   * @param  pref
   *         The preference to report
   * @param histogram
   *         The histogram ID to report to
   */
  _sendIntPrefTelemetryPing: function AUS__intTelemetryPing(pref, histogram) {
    try {
      // The getPref is already wrapped in a try/catch but we never
      // want telemetry pings breaking app update so we just put it
      // inside the try to be safe.
      let val = getPref("getIntPref", pref, 0);
      Services.telemetry.getHistogramById(histogram).add(val);
    } catch(e) {
      // Don't allow any exception to be propagated.
      Cu.reportError(e);
    }
  },


  /**
   * Submit the results of applying the update via telemetry.
   *
   * @param  status
   *         The status of the update as read from the update.status file
   */
  _sendStatusCodeTelemetryPing: function AUS__statusTelemetryPing(status) {
    try {
      let parts = status.split(":");
      if ((parts.length == 1 && status != STATE_SUCCEEDED) ||
          (parts.length > 1  && parts[0] != STATE_FAILED)) {
        // Should also report STATE_DOWNLOAD_FAILED
        return;
      }
      let result = 0; // 0 means success
      if (parts.length > 1) {
        result = parseInt(parts[1]) || INVALID_UPDATER_STATUS_CODE;
      }
      Services.telemetry.getHistogramById("UPDATER_STATUS_CODES").add(result);
    } catch(e) {
      // Don't allow any exception to be propagated.
      Cu.reportError(e);
    }
  },

  /**
   * Submit the interval in days since the last notification for this background
   * update check.
   */
  _sendLastNotifyIntervalPing: function AUS__notifyIntervalPing() {
    if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_LASTUPDATETIME)) {
      let idSuffix = this._isNotify ? "NOTIFY" : "EXTERNAL";
      let lastUpdateTimeSeconds = getPref("getIntPref",
                                          PREF_APP_UPDATE_LASTUPDATETIME, 0);
      if (lastUpdateTimeSeconds) {
        let currentTimeSeconds = Math.round(Date.now() / 1000);
        if (lastUpdateTimeSeconds > currentTimeSeconds) {
          try {
            Services.telemetry.
              getHistogramById("UPDATER_INVALID_LASTUPDATETIME_" + idSuffix).
              add(1);
          } catch(e) {
            Cu.reportError(e);
          }
        }
        else {
          let intervalDays = (currentTimeSeconds - lastUpdateTimeSeconds) /
                             (60 * 60 * 24);
          try {
            Services.telemetry.
              getHistogramById("UPDATER_INVALID_LASTUPDATETIME_" + idSuffix).
              add(0);
            Services.telemetry.
              getHistogramById("UPDATER_LAST_NOTIFY_INTERVAL_DAYS_" + idSuffix).
              add(intervalDays);
          } catch(e) {
            Cu.reportError(e);
          }
        }
      }
    }
  },

  /**
   * Submit the result for the background update check.
   *
   * @param  code
   *         An integer value as defined by the PING_BGUC_* constants.
   */
  _backgroundUpdateCheckCodePing: function AUS__backgroundUpdateCheckCodePing(code) {
    try {
      let idSuffix = this._isNotify ? "NOTIFY" : "EXTERNAL";
      Services.telemetry.
        getHistogramById("UPDATER_BACKGROUND_CHECK_CODE_" + idSuffix).add(code);
    }
    catch (e) {
      Cu.reportError(e);
    }
  },

  /**
   * Register an observer when the network comes online, so we can short-circuit
   * the app.update.interval when there isn't connectivity
   */
  _registerOnlineObserver: function AUS__registerOnlineObserver() {
    if (this._registeredOnlineObserver) {
      LOG("UpdateService:_registerOnlineObserver - observer already registered");
      return;
    }

    LOG("UpdateService:_registerOnlineObserver - waiting for the network to " +
        "be online, then forcing another check");

    Services.obs.addObserver(this, "network:offline-status-changed", false);
    this._registeredOnlineObserver = true;
  },

  /**
   * Called from the network:offline-status-changed observer.
   */
  _offlineStatusChanged: function AUS__offlineStatusChanged(status) {
    if (status !== "online") {
      return;
    }

    Services.obs.removeObserver(this, "network:offline-status-changed");
    this._registeredOnlineObserver = false;

    LOG("UpdateService:_offlineStatusChanged - network is online, forcing " +
        "another background check");

    // the background checker is contained in notify
    this._attemptResume();
  },

  onCheckComplete: function AUS_onCheckComplete(request, updates, updateCount) {
    this._selectAndInstallUpdate(updates);
  },

  onError: function AUS_onError(request, update) {
    LOG("UpdateService:onError - error during background update. error code: " +
        update.errorCode + ", status text: " + update.statusText);

    var maxErrors;
    var errCount;
    if (update.errorCode == NETWORK_ERROR_OFFLINE) {
      // Register an online observer to try again
      this._registerOnlineObserver();
      this._backgroundUpdateCheckCodePing(PING_BGUC_OFFLINE);
      return;
    }

    if (update.errorCode == CERT_ATTR_CHECK_FAILED_NO_UPDATE ||
        update.errorCode == CERT_ATTR_CHECK_FAILED_HAS_UPDATE) {
      errCount = getPref("getIntPref", PREF_APP_UPDATE_CERT_ERRORS, 0);
      errCount++;
      Services.prefs.setIntPref(PREF_APP_UPDATE_CERT_ERRORS, errCount);
      maxErrors = getPref("getIntPref", PREF_APP_UPDATE_CERT_MAXERRORS, 5);
    }
    else {
      update.errorCode = BACKGROUNDCHECK_MULTIPLE_FAILURES;
      errCount = getPref("getIntPref", PREF_APP_UPDATE_BACKGROUNDERRORS, 0);
      errCount++;
      Services.prefs.setIntPref(PREF_APP_UPDATE_BACKGROUNDERRORS, errCount);
      maxErrors = getPref("getIntPref", PREF_APP_UPDATE_BACKGROUNDMAXERRORS,
                          10);
    }

    var pingCode;
    if (errCount >= maxErrors) {
      var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                     createInstance(Ci.nsIUpdatePrompt);
      prompter.showUpdateError(update);

      switch (update.errorCode) {
        case CERT_ATTR_CHECK_FAILED_NO_UPDATE:
          pingCode = PING_BGUC_CERT_ATTR_NO_UPDATE_NOTIFY;
          break;
        case CERT_ATTR_CHECK_FAILED_HAS_UPDATE:
          pingCode = PING_BGUC_CERT_ATTR_WITH_UPDATE_NOTIFY;
          break;
        default:
          pingCode = PING_BGUC_GENERAL_ERROR_NOTIFY;
      }
    }
    else {
      switch (update.errorCode) {
        case CERT_ATTR_CHECK_FAILED_NO_UPDATE:
          pingCode = PING_BGUC_CERT_ATTR_NO_UPDATE_SILENT;
          break;
        case CERT_ATTR_CHECK_FAILED_HAS_UPDATE:
          pingCode = PING_BGUC_CERT_ATTR_WITH_UPDATE_SILENT;
          break;
        default:
          pingCode = PING_BGUC_GENERAL_ERROR_SILENT;
      }
    }
    this._backgroundUpdateCheckCodePing(pingCode);
  },

  /**
   * Called when a connection should be resumed
   */
  _attemptResume: function AUS_attemptResume() {
    LOG("UpdateService:_attemptResume")
    // If a download is in progress, then resume it.
    if (this._downloader && this._downloader._patch &&
        this._downloader._patch.state == STATE_DOWNLOADING &&
        this._downloader._update) {
      LOG("UpdateService:_attemptResume - _patch.state: " +
          this._downloader._patch.state);
      // Make sure downloading is the state for selectPatch to work correctly
      writeStatusFile(getUpdatesDir(), STATE_DOWNLOADING);
      var status = this.downloadUpdate(this._downloader._update,
                                       this._downloader.background);
      LOG("UpdateService:_attemptResume - downloadUpdate status: " + status);
      if (status == STATE_NONE) {
        cleanupActiveUpdate();
      }
      return;
    }

    this.backgroundChecker.checkForUpdates(this, false);
  },

  /**
   * Notified when a timer fires
   * @param   timer
   *          The timer that fired
   */
  notify: function AUS_notify(timer) {
    // The telemetry below is specific to background notification.
    this._sendBoolPrefTelemetryPing(PREF_APP_UPDATE_ENABLED,
                                    "UPDATER_UPDATES_ENABLED");
    this._sendBoolPrefTelemetryPing(PREF_APP_UPDATE_METRO_ENABLED,
                                    "UPDATER_UPDATES_METRO_ENABLED");
    this._sendBoolPrefTelemetryPing(PREF_APP_UPDATE_AUTO,
                                    "UPDATER_UPDATES_AUTOMATIC");
    this._sendBoolPrefTelemetryPing(PREF_APP_UPDATE_STAGING_ENABLED,
                                    "UPDATER_STAGE_ENABLED");
    this._checkForBackgroundUpdates(true);
  },

  /**
   * See nsIUpdateService.idl
   */
  checkForBackgroundUpdates: function AUS_checkForBackgroundUpdates() {
    this._checkForBackgroundUpdates(false);
  },

  /**
   * Checks for updates in the background.
   * @param   isNotify
   *          Whether or not a background update check was initiated by the
   *          application update timer notification.
   */
  _checkForBackgroundUpdates: function AUS__checkForBackgroundUpdates(isNotify) {
    this._isNotify = isNotify;
    // From this point on, the telemetry reported differentiates between a call
    // to notify and a call to checkForBackgroundUpdates so they are reported
    // separately.
    this._sendLastNotifyIntervalPing();

    // If a download is in progress or the patch has been staged do nothing.
    if (this.isDownloading) {
      this._backgroundUpdateCheckCodePing(PING_BGUC_IS_DOWNLOADING);
      return;
    }

    if (this._downloader && this._downloader.patchIsStaged) {
      this._backgroundUpdateCheckCodePing(PING_BGUC_IS_STAGED);
      return;
    }

    // The following checks will return early without notification in the call
    // to checkForUpdates below. To simplify the background update check ping
    // their values are checked here.
    try {
      if (!this.backgroundChecker.getUpdateURL(false)) {
        let prefs = Services.prefs;
        if (!prefs.prefHasUserValue(PREF_APP_UPDATE_URL_OVERRIDE)) {
          if (!prefs.prefHasUserValue(PREF_APP_UPDATE_URL)) {
            this._backgroundUpdateCheckCodePing(PING_BGUC_INVALID_DEFAULT_URL);
          }
          else {
            this._backgroundUpdateCheckCodePing(PING_BGUC_INVALID_CUSTOM_URL);
          }
        }
        else {
          this._backgroundUpdateCheckCodePing(PING_BGUC_INVALID_OVERRIDE_URL);
        }
      }
      else if (!gMetroUpdatesEnabled) {
        this._backgroundUpdateCheckCodePing(PING_BGUC_METRO_DISABLED);
      }
      else if (!getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true)) {
        this._backgroundUpdateCheckCodePing(PING_BGUC_PREF_DISABLED);
      }
      else if (!(gCanCheckForUpdates && hasUpdateMutex())) {
        this._backgroundUpdateCheckCodePing(PING_BGUC_UNABLE_TO_CHECK);
      }
      else if (!this.backgroundChecker._enabled) {
        this._backgroundUpdateCheckCodePing(PING_BGUC_DISABLED_FOR_SESSION);
      }
    }
    catch (e) {
      Cu.reportError(e);
    }

    this.backgroundChecker.checkForUpdates(this, false);
  },

  /**
   * Determine the update from the specified updates that should be offered.
   * If both valid major and minor updates are available the minor update will
   * be offered.
   * @param   updates
   *          An array of available nsIUpdate items
   * @return  The nsIUpdate to offer.
   */
  selectUpdate: function AUS_selectUpdate(updates) {
    if (updates.length == 0) {
      this._backgroundUpdateCheckCodePing(PING_BGUC_NO_UPDATE_FOUND);
      return null;
    }

    // The ping for unsupported is sent after the call to showPrompt.
    if (updates.length == 1 && updates[0].unsupported)
      return updates[0];

    // Choose the newest of the available minor and major updates.
    var majorUpdate = null;
    var minorUpdate = null;
    var vc = Services.vc;
    var lastPingCode = PING_BGUC_NO_COMPAT_UPDATE_FOUND;

    updates.forEach(function(aUpdate) {
      // Ignore updates for older versions of the applications and updates for
      // the same version or build id of the application.
      if (vc.compare(aUpdate.appVersion, Services.appinfo.version) < 0 ||
          (vc.compare(aUpdate.appVersion, Services.appinfo.version) == 0 &&
          aUpdate.buildID <= Services.appinfo.appBuildID) ||
          (vc.compare(aUpdate.appVersion, Services.appinfo.version) == 0 &&
          aUpdate.buildID == undefined)) {
        LOG("UpdateService:selectUpdate - skipping update because the " +
            "update's application version or build id is less than or the " +
            "same as the current application version or build id");
        lastPingCode = PING_BGUC_UPDATE_PREVIOUS_VERSION;
        return;
      }

      // Skip the update if the user responded with "never" to this update's
      // application version and the update specifies showNeverForVersion
      // (see bug 350636).
      let neverPrefName = PREF_APP_UPDATE_NEVER_BRANCH + aUpdate.appVersion;
      if (aUpdate.showNeverForVersion &&
          getPref("getBoolPref", neverPrefName, false)) {
        LOG("UpdateService:selectUpdate - skipping update because the " +
            "preference " + neverPrefName + " is true");
        lastPingCode = PING_BGUC_UPDATE_NEVER_PREF;
        return;
      }

      switch (aUpdate.type) {
        case "major":
          if (!majorUpdate)
            majorUpdate = aUpdate;
          else if (vc.compare(majorUpdate.appVersion, aUpdate.appVersion) <= 0)
            majorUpdate = aUpdate;
          break;
        case "minor":
          if (!minorUpdate)
            minorUpdate = aUpdate;
          else if (vc.compare(minorUpdate.appVersion, aUpdate.appVersion) <= 0)
            minorUpdate = aUpdate;
          break;
        default:
          LOG("UpdateService:selectUpdate - skipping unknown update type: " +
              aUpdate.type);
          lastPingCode = PING_BGUC_UPDATE_INVALID_TYPE;
          break;
      }
    });

    var update = minorUpdate || majorUpdate;
    if (!update)
      this._backgroundUpdateCheckCodePing(lastPingCode);

    return update;
  },

  /**
   * Reference to the currently selected update for when add-on compatibility
   * is checked.
   */
  _update: null,

  /**
   * Determine which of the specified updates should be installed and begin the
   * download/installation process or notify the user about the update.
   * @param   updates
   *          An array of available updates
   */
  _selectAndInstallUpdate: function AUS__selectAndInstallUpdate(updates) {
    // Return early if there's an active update. The user is already aware and
    // is downloading or performed some user action to prevent notification.
    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);
    if (um.activeUpdate) {
#ifdef MOZ_WIDGET_GONK
      // For gonk, the user isn't necessarily aware of the update, so we need
      // to show the prompt to make sure.
      this._showPrompt(um.activeUpdate);
#endif
      this._backgroundUpdateCheckCodePing(PING_BGUC_HAS_ACTIVEUPDATE);
      return;
    }

    var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
    if (!updateEnabled) {
      this._backgroundUpdateCheckCodePing(PING_BGUC_PREF_DISABLED);
      LOG("UpdateService:_selectAndInstallUpdate - not prompting because " +
          "update is disabled");
      return;
    }

    if (!gMetroUpdatesEnabled) {
      this._backgroundUpdateCheckCodePing(PING_BGUC_METRO_DISABLED);
      return;
    }

    var update = this.selectUpdate(updates, updates.length);
    if (!update) {
      return;
    }

    if (update.unsupported) {
      LOG("UpdateService:_selectAndInstallUpdate - update not supported for " +
          "this system");
      if (!getPref("getBoolPref", PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED, false)) {
        LOG("UpdateService:_selectAndInstallUpdate - notifying that the " +
            "update is not supported for this system");
        this._showPrompt(update);
      }
      this._backgroundUpdateCheckCodePing(PING_BGUC_UNSUPPORTED);
      return;
    }

    if (!(getCanApplyUpdates() && hasUpdateMutex())) {
      LOG("UpdateService:_selectAndInstallUpdate - the user is unable to " +
          "apply updates... prompting");
      this._showPrompt(update);
      this._backgroundUpdateCheckCodePing(PING_BGUC_UNABLE_TO_APPLY);
      return;
    }

    /**
#      From this point on there are two possible outcomes:
#      1. download and install the update automatically
#      2. notify the user about the availability of an update
#
#      Notes:
#      a) if the app.update.auto preference is false then automatic download and
#         install is disabled and the user will be notified.
#      b) if the update has a showPrompt attribute the user will be notified.
#      c) Mode is determined by the value of the app.update.mode preference.
#
#      If the update when it is first read has an appVersion attribute the
#      following behavior implemented in bug 530872 will occur:
#      Mode   Incompatible Add-ons   Outcome
#      0      N/A                    Auto Install
#      1      Yes                    Notify
#      1      No                     Auto Install
#
#      If the update when it is first read does not have an appVersion attribute
#      the following deprecated behavior will occur:
#      Update Type   Mode   Incompatible Add-ons   Outcome
#      Major         all    N/A                    Notify
#      Minor         0      N/A                    Auto Install
#      Minor         1      Yes                    Notify
#      Minor         1      No                     Auto Install
     */
    if (update.showPrompt) {
      LOG("UpdateService:_selectAndInstallUpdate - prompting because the " +
          "update snippet specified showPrompt");
      this._showPrompt(update);
      if (!Services.metro || !Services.metro.immersive) {
        this._backgroundUpdateCheckCodePing(PING_BGUC_SHOWPROMPT_SNIPPET);
        return;
      }
    }

    if (!getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true)) {
      LOG("UpdateService:_selectAndInstallUpdate - prompting because silent " +
          "install is disabled");
      this._showPrompt(update);
      if (!Services.metro || !Services.metro.immersive) {
        this._backgroundUpdateCheckCodePing(PING_BGUC_SHOWPROMPT_PREF);
        return;
      }
    }

    if (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1) == 0) {
      // Do not prompt regardless of add-on incompatibilities
      LOG("UpdateService:_selectAndInstallUpdate - add-on compatibility " +
          "check disabled by preference, just download the update");
      var status = this.downloadUpdate(update, true);
      if (status == STATE_NONE)
        cleanupActiveUpdate();
      this._backgroundUpdateCheckCodePing(PING_BGUC_ADDON_PREF_DISABLED);
      return;
    }

    // Only check add-on compatibility when the version changes.
    if (update.appVersion &&
        Services.vc.compare(update.appVersion, Services.appinfo.version) != 0) {
      this._update = update;
      this._checkAddonCompatibility();
    }
    else {
      LOG("UpdateService:_selectAndInstallUpdate - add-on compatibility " +
          "check not performed due to the update version being the same as " +
          "the current application version, just download the update");
      var status = this.downloadUpdate(update, true);
      if (status == STATE_NONE)
        cleanupActiveUpdate();
      this._backgroundUpdateCheckCodePing(PING_BGUC_ADDON_SAME_APP_VER);
    }
  },

  _showPrompt: function AUS__showPrompt(update) {
    var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                   createInstance(Ci.nsIUpdatePrompt);
    prompter.showUpdateAvailable(update);
  },

  _checkAddonCompatibility: function AUS__checkAddonCompatibility() {
    try {
      var hotfixID = Services.prefs.getCharPref(PREF_EM_HOTFIX_ID);
    }
    catch (e) { }

    // Get all the installed add-ons
    var self = this;
    AddonManager.getAllAddons(function(addons) {
      self._incompatibleAddons = [];
      addons.forEach(function(addon) {
        // Protect against code that overrides the add-ons manager and doesn't
        // implement the isCompatibleWith or the findUpdates method.
        if (!("isCompatibleWith" in addon) || !("findUpdates" in addon)) {
          let errMsg = "Add-on doesn't implement either the isCompatibleWith " +
                       "or the findUpdates method!";
          if (addon.id)
            errMsg += " Add-on ID: " + addon.id;
          Cu.reportError(errMsg);
          return;
        }

        // If an add-on isn't appDisabled and isn't userDisabled then it is
        // either active now or the user expects it to be active after the
        // restart. If that is the case and the add-on is not installed by the
        // application and is not compatible with the new application version
        // then the user should be warned that the add-on will become
        // incompatible. If an addon's type equals plugin it is skipped since
        // checking plugins compatibility information isn't supported and
        // getting the scope property of a plugin breaks in some environments
        // (see bug 566787). The hotfix add-on is also ignored as it shouldn't
        // block the user from upgrading.
        try {
          if (addon.type != "plugin" && addon.id != hotfixID &&
              !addon.appDisabled && !addon.userDisabled &&
              addon.scope != AddonManager.SCOPE_APPLICATION &&
              addon.isCompatible &&
              !addon.isCompatibleWith(self._update.appVersion,
                                      self._update.platformVersion))
            self._incompatibleAddons.push(addon);
        }
        catch (e) {
          Cu.reportError(e);
        }
      });

      if (self._incompatibleAddons.length > 0) {
      /**
#        PREF_APP_UPDATE_INCOMPATIBLE_MODE
#        Controls the mode in which we check for updates as follows.
#
#          PREF_APP_UPDATE_INCOMPATIBLE_MODE != 1
#          We check for VersionInfo _and_ NewerVersion updates for the
#          incompatible add-ons - i.e. if Foo 1.2 is installed and it is
#          incompatible with the update, and we find Foo 2.0 which is but has
#          not been installed, then we do NOT prompt because the user can
#          download Foo 2.0 when they restart after the update during the add-on
#          mismatch checking UI. This is the default, since it suppresses most
#          prompt dialogs.
#
#          PREF_APP_UPDATE_INCOMPATIBLE_MODE == 1
#          We check for VersionInfo updates for the incompatible add-ons - i.e.
#          if the situation above with Foo 1.2 and available update to 2.0
#          applies, we DO show the prompt since a download operation will be
#          required after the update. This is not the default and is supplied
#          only as a hidden option for those that want it.
       */
        self._updateCheckCount = self._incompatibleAddons.length;
        LOG("UpdateService:_checkAddonCompatibility - checking for " +
            "incompatible add-ons");

        self._incompatibleAddons.forEach(function(addon) {
          addon.findUpdates(this, AddonManager.UPDATE_WHEN_NEW_APP_DETECTED,
                            this._update.appVersion, this._update.platformVersion);
        }, self);
      }
      else {
        LOG("UpdateService:_checkAddonCompatibility - no incompatible " +
            "add-ons found, just download the update");
        var status = self.downloadUpdate(self._update, true);
        if (status == STATE_NONE)
          cleanupActiveUpdate();
        self._update = null;
        self._backgroundUpdateCheckCodePing(PING_BGUC_CHECK_NO_INCOMPAT);
      }
    });
  },

  // AddonUpdateListener
  onCompatibilityUpdateAvailable: function(addon) {
    // Remove the add-on from the list of add-ons that will become incompatible
    // with the new version of the application.
    for (var i = 0; i < this._incompatibleAddons.length; ++i) {
      if (this._incompatibleAddons[i].id == addon.id) {
        LOG("UpdateService:onCompatibilityUpdateAvailable - found update for " +
            "add-on ID: " + addon.id);
        this._incompatibleAddons.splice(i, 1);
      }
    }
  },

  onUpdateAvailable: function(addon, install) {
    if (getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 0) == 1)
      return;

    // If the new version of this add-on is blocklisted for the new application
    // then it isn't a valid update and the user should still be warned that
    // the add-on will become incompatible.
    let bs = Cc["@mozilla.org/extensions/blocklist;1"].
             getService(Ci.nsIBlocklistService);
    if (bs.isAddonBlocklisted(addon,
                              this._update.appVersion,
                              this._update.platformVersion))
      return;

    // Compatibility or new version updates mean the same thing here.
    this.onCompatibilityUpdateAvailable(addon);
  },

  onUpdateFinished: function(addon) {
    if (--this._updateCheckCount > 0)
      return;

    if (this._incompatibleAddons.length > 0 ||
        !(getCanApplyUpdates() && hasUpdateMutex())) {
      LOG("UpdateService:onUpdateEnded - prompting because there are " +
          "incompatible add-ons");
      this._showPrompt(this._update);
      this._backgroundUpdateCheckCodePing(PING_BGUC_ADDON_HAVE_INCOMPAT);
    }
    else {
      LOG("UpdateService:_selectAndInstallUpdate - updates for all " +
          "incompatible add-ons found, just download the update");
      var status = this.downloadUpdate(this._update, true);
      if (status == STATE_NONE)
        cleanupActiveUpdate();
      this._backgroundUpdateCheckCodePing(PING_BGUC_ADDON_UPDATES_FOR_INCOMPAT);
    }
    this._update = null;
  },

  /**
   * The Checker used for background update checks.
   */
  _backgroundChecker: null,

  /**
   * See nsIUpdateService.idl
   */
  get backgroundChecker() {
    if (!this._backgroundChecker)
      this._backgroundChecker = new Checker();
    return this._backgroundChecker;
  },

  /**
   * See nsIUpdateService.idl
   */
  get canCheckForUpdates() {
    return gCanCheckForUpdates && hasUpdateMutex();
  },

  /**
   * See nsIUpdateService.idl
   */
  get canApplyUpdates() {
    return getCanApplyUpdates() && hasUpdateMutex();
  },

  /**
   * See nsIUpdateService.idl
   */
  get canStageUpdates() {
    return getCanStageUpdates();
  },

  /**
   * See nsIUpdateService.idl
   */
  get isOtherInstanceHandlingUpdates() {
    return !hasUpdateMutex();
  },


  /**
   * See nsIUpdateService.idl
   */
  addDownloadListener: function AUS_addDownloadListener(listener) {
    if (!this._downloader) {
      LOG("UpdateService:addDownloadListener - no downloader!");
      return;
    }
    this._downloader.addDownloadListener(listener);
  },

  /**
   * See nsIUpdateService.idl
   */
  removeDownloadListener: function AUS_removeDownloadListener(listener) {
    if (!this._downloader) {
      LOG("UpdateService:removeDownloadListener - no downloader!");
      return;
    }
    this._downloader.removeDownloadListener(listener);
  },

  /**
   * See nsIUpdateService.idl
   */
  downloadUpdate: function AUS_downloadUpdate(update, background) {
    if (!update)
      throw Cr.NS_ERROR_NULL_POINTER;

    // Don't download the update if the update's version is less than the
    // current application's version or the update's version is the same as the
    // application's version and the build ID is the same as the application's
    // build ID.
    if (update.appVersion &&
        (Services.vc.compare(update.appVersion, Services.appinfo.version) < 0 ||
         update.buildID && update.buildID == Services.appinfo.appBuildID &&
         update.appVersion == Services.appinfo.version)) {
      LOG("UpdateService:downloadUpdate - canceling download of update since " +
          "it is for an earlier or same application version and build ID.\n" +
          "current application version: " + Services.appinfo.version + "\n" +
          "update application version : " + update.appVersion + "\n" +
          "current build ID: " + Services.appinfo.appBuildID + "\n" +
          "update build ID : " + update.buildID);
      cleanupActiveUpdate();
      return STATE_NONE;
    }

    // If a download request is in progress vs. a download ready to resume
    if (this.isDownloading) {
      if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
          background == this._downloader.background) {
        LOG("UpdateService:downloadUpdate - no support for downloading more " +
            "than one update at a time");
        return readStatusFile(getUpdatesDir());
      }
      this._downloader.cancel();
    }
#ifdef MOZ_WIDGET_GONK
    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);
    var activeUpdate = um.activeUpdate;
    if (activeUpdate &&
        (activeUpdate.appVersion != update.appVersion ||
         activeUpdate.buildID != update.buildID)) {
      // We have an activeUpdate (which presumably was interrupted), and are
      // about start downloading a new one. Make sure we remove all traces
      // of the active one (otherwise we'll start appending the new update.mar
      // the the one that's been partially downloaded).
      LOG("UpdateService:downloadUpdate - removing stale active update.");
      cleanupActiveUpdate();
    }
#endif
    // Set the previous application version prior to downloading the update.
    update.previousAppVersion = Services.appinfo.version;
    this._downloader = new Downloader(background, this);
    return this._downloader.downloadUpdate(update);
  },

  /**
   * See nsIUpdateService.idl
   */
  pauseDownload: function AUS_pauseDownload() {
    if (this.isDownloading) {
      this._downloader.cancel();
    } else if (this._retryTimer) {
      // Download status is still consider as 'downloading' during retry.
      // We need to cancel both retry and download at this stage.
      this._retryTimer.cancel();
      this._retryTimer = null;
      this._downloader.cancel();
    }
  },

  /**
   * See nsIUpdateService.idl
   */
  getUpdatesDirectory: getUpdatesDir,

  /**
   * See nsIUpdateService.idl
   */
  get isDownloading() {
    return this._downloader && this._downloader.isBusy;
  },

  /**
   * See nsIUpdateService.idl
   */
  applyOsUpdate: function AUS_applyOsUpdate(aUpdate) {
    if (!aUpdate.isOSUpdate || aUpdate.state != STATE_APPLIED) {
      aUpdate.statusText = "fota-state-error";
      throw Cr.NS_ERROR_FAILURE;
    }

    let osApplyToDir;
    try {
      aUpdate.QueryInterface(Ci.nsIWritablePropertyBag);
      osApplyToDir = aUpdate.getProperty("osApplyToDir");
    } catch (e) {}

    if (!osApplyToDir) {
      LOG("UpdateService:applyOsUpdate - Error: osApplyToDir is not defined" +
          "in the nsIUpdate!");
      handleUpdateFailure(aUpdate, FOTA_FILE_OPERATION_ERROR);
      return;
    }

    let updateFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
    updateFile.initWithPath(osApplyToDir + "/update.zip");
    if (!updateFile.exists()) {
      LOG("UpdateService:applyOsUpdate - Error: OS update is not found at " +
          updateFile.path);
      handleUpdateFailure(aUpdate, FOTA_FILE_OPERATION_ERROR);
      return;
    }

    writeStatusFile(getUpdatesDir(), aUpdate.state = STATE_APPLIED_OS);
    LOG("UpdateService:applyOsUpdate - Rebooting into recovery to apply " +
        "FOTA update: " + updateFile.path);
    try {
      let recoveryService = Cc["@mozilla.org/recovery-service;1"]
                            .getService(Ci.nsIRecoveryService);
      recoveryService.installFotaUpdate(updateFile.path);
    } catch (e) {
      LOG("UpdateService:applyOsUpdate - Error: Couldn't reboot into recovery" +
          " to apply FOTA update " + updateFile.path);
      writeStatusFile(getUpdatesDir(), aUpdate.state = STATE_APPLIED);
      handleUpdateFailure(aUpdate, FOTA_RECOVERY_ERROR);
    }
  },

  classID: UPDATESERVICE_CID,
  classInfo: XPCOMUtils.generateCI({classID: UPDATESERVICE_CID,
                                    contractID: UPDATESERVICE_CONTRACTID,
                                    interfaces: [Ci.nsIApplicationUpdateService,
                                                 Ci.nsITimerCallback,
                                                 Ci.nsIObserver],
                                    flags: Ci.nsIClassInfo.SINGLETON}),

  _xpcom_factory: UpdateServiceFactory,
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIApplicationUpdateService,
                                         Ci.nsIUpdateCheckListener,
                                         Ci.nsITimerCallback,
                                         Ci.nsIObserver])
};

/**
 * A service to manage active and past updates.
 * @constructor
 */
function UpdateManager() {
  // Ensure the Active Update file is loaded
  var updates = this._loadXMLFileIntoArray(getUpdateFile(
                  [FILE_UPDATE_ACTIVE]));
  if (updates.length > 0) {
    // Under some edgecases such as Windows system restore the active-update.xml
    // will contain a pending update without the status file which will return
    // STATE_NONE. To recover from this situation clean the updates dir and
    // rewrite the active-update.xml file without the broken update.
    if (readStatusFile(getUpdatesDir()) == STATE_NONE) {
      cleanUpUpdatesDir();
      this._writeUpdatesToXMLFile([], getUpdateFile([FILE_UPDATE_ACTIVE]));
    }
    else
      this._activeUpdate = updates[0];
  }
}
UpdateManager.prototype = {
  /**
   * All previously downloaded and installed updates, as an array of nsIUpdate
   * objects.
   */
  _updates: null,

  /**
   * The current actively downloading/installing update, as a nsIUpdate object.
   */
  _activeUpdate: null,

  /**
   * Handle Observer Service notifications
   * @param   subject
   *          The subject of the notification
   * @param   topic
   *          The notification name
   * @param   data
   *          Additional data
   */
  observe: function UM_observe(subject, topic, data) {
    // Hack to be able to run and cleanup tests by reloading the update data.
    if (topic == "um-reload-update-data") {
      this._updates = this._loadXMLFileIntoArray(getUpdateFile(
                        [FILE_UPDATES_DB]));
      this._activeUpdate = null;
      var updates = this._loadXMLFileIntoArray(getUpdateFile(
                      [FILE_UPDATE_ACTIVE]));
      if (updates.length > 0)
        this._activeUpdate = updates[0];
    }
  },

  /**
   * Loads an updates.xml formatted file into an array of nsIUpdate items.
   * @param   file
   *          A nsIFile for the updates.xml file
   * @return  The array of nsIUpdate items held in the file.
   */
  _loadXMLFileIntoArray: function UM__loadXMLFileIntoArray(file) {
    if (!file.exists()) {
      LOG("UpdateManager:_loadXMLFileIntoArray: XML file does not exist");
      return [];
    }

    var result = [];
    var fileStream = Cc["@mozilla.org/network/file-input-stream;1"].
                     createInstance(Ci.nsIFileInputStream);
    fileStream.init(file, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0);
    try {
      var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
                   createInstance(Ci.nsIDOMParser);
      var doc = parser.parseFromStream(fileStream, "UTF-8",
                                       fileStream.available(), "text/xml");

      const ELEMENT_NODE = Ci.nsIDOMNode.ELEMENT_NODE;
      var updateCount = doc.documentElement.childNodes.length;
      for (var i = 0; i < updateCount; ++i) {
        var updateElement = doc.documentElement.childNodes.item(i);
        if (updateElement.nodeType != ELEMENT_NODE ||
            updateElement.localName != "update")
          continue;

        updateElement.QueryInterface(Ci.nsIDOMElement);
        try {
          var update = new Update(updateElement);
        } catch (e) {
          LOG("UpdateManager:_loadXMLFileIntoArray - invalid update");
          continue;
        }
        result.push(update);
      }
    }
    catch (e) {
      LOG("UpdateManager:_loadXMLFileIntoArray - error constructing update " +
          "list. Exception: " + e);
    }
    fileStream.close();
    return result;
  },

  /**
   * Load the update manager, initializing state from state files.
   */
  _ensureUpdates: function UM__ensureUpdates() {
    if (!this._updates) {
      this._updates = this._loadXMLFileIntoArray(getUpdateFile(
                        [FILE_UPDATES_DB]));
      var activeUpdates = this._loadXMLFileIntoArray(getUpdateFile(
                            [FILE_UPDATE_ACTIVE]));
      if (activeUpdates.length > 0)
        this._activeUpdate = activeUpdates[0];
    }
  },

  /**
   * See nsIUpdateService.idl
   */
  getUpdateAt: function UM_getUpdateAt(index) {
    this._ensureUpdates();
    return this._updates[index];
  },

  /**
   * See nsIUpdateService.idl
   */
  get updateCount() {
    this._ensureUpdates();
    return this._updates.length;
  },

  /**
   * See nsIUpdateService.idl
   */
  get activeUpdate() {
    if (this._activeUpdate &&
        this._activeUpdate.channel != UpdateChannel.get()) {
      LOG("UpdateManager:get activeUpdate - channel has changed, " +
          "reloading default preferences to workaround bug 802022");
      // Workaround to get distribution preferences loaded (Bug 774618). This
      // can be removed after bug 802022 is fixed.
      let prefSvc = Services.prefs.QueryInterface(Ci.nsIObserver);
      prefSvc.observe(null, "reload-default-prefs", null);
      if (this._activeUpdate.channel != UpdateChannel.get()) {
        // User switched channels, clear out any old active updates and remove
        // partial downloads
        this._activeUpdate = null;
        this.saveUpdates();

        // Destroy the updates directory, since we're done with it.
        cleanUpUpdatesDir();
      }
    }
    return this._activeUpdate;
  },
  set activeUpdate(activeUpdate) {
    this._addUpdate(activeUpdate);
    this._activeUpdate = activeUpdate;
    if (!activeUpdate) {
      // If |activeUpdate| is null, we have updated both lists - the active list
      // and the history list, so we want to write both files.
      this.saveUpdates();
    }
    else
      this._writeUpdatesToXMLFile([this._activeUpdate],
                                  getUpdateFile([FILE_UPDATE_ACTIVE]));
    return activeUpdate;
  },

  /**
   * Add an update to the Updates list. If the item already exists in the list,
   * replace the existing value with the new value.
   * @param   update
   *          The nsIUpdate object to add.
   */
  _addUpdate: function UM__addUpdate(update) {
    if (!update)
      return;
    this._ensureUpdates();
    if (this._updates) {
      for (var i = 0; i < this._updates.length; ++i) {
        if (this._updates[i] &&
            this._updates[i].appVersion == update.appVersion &&
            this._updates[i].buildID == update.buildID) {
          // Replace the existing entry with the new value, updating
          // all metadata.
          this._updates[i] = update;
          return;
        }
      }
    }
    // Otherwise add it to the front of the list.
    this._updates.unshift(update);
  },

  /**
   * Serializes an array of updates to an XML file
   * @param   updates
   *          An array of nsIUpdate objects
   * @param   file
   *          The nsIFile object to serialize to
   */
  _writeUpdatesToXMLFile: function UM__writeUpdatesToXMLFile(updates, file) {
    var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
              createInstance(Ci.nsIFileOutputStream);
    var modeFlags = FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE |
                    FileUtils.MODE_TRUNCATE;
    if (!file.exists())
      file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
    fos.init(file, modeFlags, FileUtils.PERMS_FILE, 0);

    try {
      var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
                   createInstance(Ci.nsIDOMParser);
      const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
      var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");

      for (var i = 0; i < updates.length; ++i) {
        if (updates[i])
          doc.documentElement.appendChild(updates[i].serialize(doc));
      }

      var serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].
                       createInstance(Ci.nsIDOMSerializer);
      serializer.serializeToStream(doc.documentElement, fos, null);
    }
    catch (e) {
    }

    FileUtils.closeSafeFileOutputStream(fos);
  },

  /**
   * See nsIUpdateService.idl
   */
  saveUpdates: function UM_saveUpdates() {
    this._writeUpdatesToXMLFile([this._activeUpdate],
                                getUpdateFile([FILE_UPDATE_ACTIVE]));
    if (this._activeUpdate)
      this._addUpdate(this._activeUpdate);

    this._ensureUpdates();
    // Don't write updates that have a temporary state to the updates.xml file.
    if (this._updates) {
      let updates = this._updates.slice();
      for (let i = updates.length - 1; i >= 0; --i) {
        let state = updates[i].state;
        if (state == STATE_NONE || state == STATE_DOWNLOADING ||
            state == STATE_APPLIED || state == STATE_PENDING) {
          updates.splice(i, 1);
        }
      }

      this._writeUpdatesToXMLFile(updates.slice(0, 10),
                                  getUpdateFile([FILE_UPDATES_DB]));
    }
  },

  /**
   * See nsIUpdateService.idl
   */
  refreshUpdateStatus: function UM_refreshUpdateStatus(aUpdate) {
    var update = this._activeUpdate ? this._activeUpdate : aUpdate;
    var updateSucceeded = true;
    var status = readStatusFile(getUpdatesDir());
    var ary = status.split(":");
    update.state = ary[0];
    if (update.state == STATE_FAILED && ary[1]) {
      updateSucceeded = false;
      if (!handleUpdateFailure(update, ary[1])) {
        handleFallbackToCompleteUpdate(update, true);
      }
    }
    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);
    um.saveUpdates();

    if (update.state != STATE_PENDING) {
      // Destroy the updates directory, since we're done with it.
      // Make sure to not do this when the updater has fallen back to
      // non-staged updates.
      cleanUpUpdatesDir(updateSucceeded);
    }

    // Send an observer notification which the update wizard uses in
    // order to update its UI.
    LOG("UpdateManager:refreshUpdateStatus - Notifying observers that " +
        "the update was staged. state: " + update.state + ", status: " + status);
    Services.obs.notifyObservers(null, "update-staged", update.state);

    // Do this after *everything* else, since it will likely cause the app
    // to shut down.
#ifdef MOZ_WIDGET_GONK
    if (update.state == STATE_APPLIED) {
      // Notify the user that an update has been staged and is ready for
      // installation (i.e. that they should restart the application). We do
      // not notify on failed update attempts.
      var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                     createInstance(Ci.nsIUpdatePrompt);
      prompter.showUpdateDownloaded(update, true);
    } else {
      releaseSDCardMountLock();
    }
#else
    // Only prompt when the UI isn't already open.
    let windowType = getPref("getCharPref", PREF_APP_UPDATE_ALTWINDOWTYPE, null);
    if (Services.wm.getMostRecentWindow(UPDATE_WINDOW_NAME) ||
        windowType && Services.wm.getMostRecentWindow(windowType)) {
      return;
    }

    if (update.state == STATE_APPLIED || update.state == STATE_PENDING) {
      // Notify the user that an update has been staged and is ready for
      // installation (i.e. that they should restart the application).
      var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                     createInstance(Ci.nsIUpdatePrompt);
      prompter.showUpdateDownloaded(update, true);
    }
#endif
  },

  classID: Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateManager, Ci.nsIObserver])
};

/**
 * Checker
 * Checks for new Updates
 * @constructor
 */
function Checker() {
}
Checker.prototype = {
  /**
   * The XMLHttpRequest object that performs the connection.
   */
  _request  : null,

  /**
   * The nsIUpdateCheckListener callback
   */
  _callback : null,

  /**
   * The URL of the update service XML file to connect to that contains details
   * about available updates.
   */
  getUpdateURL: function UC_getUpdateURL(force) {
    this._forced = force;

    // Use the override URL if specified.
    var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);

    // Otherwise, construct the update URL from component parts.
    if (!url) {
      try {
        url = Services.prefs.getDefaultBranch(null).
              getCharPref(PREF_APP_UPDATE_URL);
      } catch (e) {
      }
    }

    if (!url || url == "") {
      LOG("Checker:getUpdateURL - update URL not defined");
      return null;
    }

    url = url.replace(/%PRODUCT%/g, Services.appinfo.name);
    url = url.replace(/%VERSION%/g, Services.appinfo.version);
    url = url.replace(/%BUILD_ID%/g, Services.appinfo.appBuildID);
    url = url.replace(/%BUILD_TARGET%/g, Services.appinfo.OS + "_" + gABI);
    url = url.replace(/%OS_VERSION%/g, gOSVersion);
    if (/%LOCALE%/.test(url))
      url = url.replace(/%LOCALE%/g, getLocale());
    url = url.replace(/%CHANNEL%/g, UpdateChannel.get());
    url = url.replace(/%PLATFORM_VERSION%/g, Services.appinfo.platformVersion);
    url = url.replace(/%DISTRIBUTION%/g,
                      getDistributionPrefValue(PREF_APP_DISTRIBUTION));
    url = url.replace(/%DISTRIBUTION_VERSION%/g,
                      getDistributionPrefValue(PREF_APP_DISTRIBUTION_VERSION));
    url = url.replace(/%CUSTOM%/g, getPref("getCharPref", PREF_APP_UPDATE_CUSTOM, ""));
    url = url.replace(/\+/g, "%2B");

#ifdef MOZ_WIDGET_GONK
    url = url.replace(/%PRODUCT_MODEL%/g, gProductModel);
    url = url.replace(/%PRODUCT_DEVICE%/g, gProductDevice);
    url = url.replace(/%B2G_VERSION%/g, getPref("getCharPref", PREF_APP_B2G_VERSION, null));
#endif

    if (force)
      url += (url.indexOf("?") != -1 ? "&" : "?") + "force=1";

    LOG("Checker:getUpdateURL - update URL: " + url);
    return url;
  },

  /**
   * See nsIUpdateService.idl
   */
  checkForUpdates: function UC_checkForUpdates(listener, force) {
    LOG("Checker: checkForUpdates, force: " + force);
    if (!listener)
      throw Cr.NS_ERROR_NULL_POINTER;

    Services.obs.notifyObservers(null, "update-check-start", null);

    var url = this.getUpdateURL(force);
    if (!url || (!this.enabled && !force))
      return;

    recordInHealthReport(UpdaterHealthReportFields.CHECK_START, 0);

    this._request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
                    createInstance(Ci.nsISupports);
    // This is here to let unit test code override XHR
    if (this._request.wrappedJSObject) {
      this._request = this._request.wrappedJSObject;
    }
    this._request.open("GET", url, true);
    var allowNonBuiltIn = !getPref("getBoolPref",
                                   PREF_APP_UPDATE_CERT_REQUIREBUILTIN, true);
    this._request.channel.notificationCallbacks = new gCertUtils.BadCertHandler(allowNonBuiltIn);
    // Prevent the request from reading from the cache.
    this._request.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
    // Prevent the request from writing to the cache.
    this._request.channel.loadFlags |= Ci.nsIRequest.INHIBIT_CACHING;

    this._request.overrideMimeType("text/xml");
    // The Cache-Control header is only interpreted by proxies and the
    // final destination. It does not help if a resource is already
    // cached locally.
    this._request.setRequestHeader("Cache-Control", "no-cache");
    // HTTP/1.0 servers might not implement Cache-Control and
    // might only implement Pragma: no-cache
    this._request.setRequestHeader("Pragma", "no-cache");

    var self = this;
    this._request.addEventListener("error", function(event) { self.onError(event); } ,false);
    this._request.addEventListener("load", function(event) { self.onLoad(event); }, false);

    LOG("Checker:checkForUpdates - sending request to: " + url);
    this._request.send(null);

    this._callback = listener;
  },

  /**
   * Returns an array of nsIUpdate objects discovered by the update check.
   * @throws if the XML document element node name is not updates.
   */
  get _updates() {
    var updatesElement = this._request.responseXML.documentElement;
    if (!updatesElement) {
      LOG("Checker:_updates get - empty updates document?!");
      return [];
    }

    if (updatesElement.nodeName != "updates") {
      LOG("Checker:_updates get - unexpected node name!");
      throw new Error("Unexpected node name, expected: updates, got: " +
                      updatesElement.nodeName);
    }

    const ELEMENT_NODE = Ci.nsIDOMNode.ELEMENT_NODE;
    var updates = [];
    for (var i = 0; i < updatesElement.childNodes.length; ++i) {
      var updateElement = updatesElement.childNodes.item(i);
      if (updateElement.nodeType != ELEMENT_NODE ||
          updateElement.localName != "update")
        continue;

      updateElement.QueryInterface(Ci.nsIDOMElement);
      try {
        var update = new Update(updateElement);
      } catch (e) {
        LOG("Checker:_updates get - invalid <update/>, ignoring...");
        continue;
      }
      update.serviceURL = this.getUpdateURL(this._forced);
      update.channel = UpdateChannel.get();
      updates.push(update);
    }

    return updates;
  },

  /**
   * Returns the status code for the XMLHttpRequest
   */
  _getChannelStatus: function UC__getChannelStatus(request) {
    var status = 0;
    try {
      status = request.status;
    }
    catch (e) {
    }

    if (status == 0)
      status = request.channel.QueryInterface(Ci.nsIRequest).status;
    return status;
  },

  _isHttpStatusCode: function UC__isHttpStatusCode(status) {
    return status >= 100 && status <= 599;
  },

  /**
   * The XMLHttpRequest succeeded and the document was loaded.
   * @param   event
   *          The nsIDOMEvent for the load
   */
  onLoad: function UC_onLoad(event) {
    LOG("Checker:onLoad - request completed downloading document");

    var prefs = Services.prefs;
    var certs = null;
    if (!prefs.prefHasUserValue(PREF_APP_UPDATE_URL_OVERRIDE) &&
        getPref("getBoolPref", PREF_APP_UPDATE_CERT_CHECKATTRS, true)) {
      certs = gCertUtils.readCertPrefs(PREF_APP_UPDATE_CERTS_BRANCH);
    }

    try {
      // Analyze the resulting DOM and determine the set of updates.
      var updates = this._updates;
      LOG("Checker:onLoad - number of updates available: " + updates.length);
      var allowNonBuiltIn = !getPref("getBoolPref",
                                     PREF_APP_UPDATE_CERT_REQUIREBUILTIN, true);
      gCertUtils.checkCert(this._request.channel, allowNonBuiltIn, certs);

      if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_CERT_ERRORS))
        Services.prefs.clearUserPref(PREF_APP_UPDATE_CERT_ERRORS);

      if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_BACKGROUNDERRORS))
        Services.prefs.clearUserPref(PREF_APP_UPDATE_BACKGROUNDERRORS);

      recordInHealthReport(UpdaterHealthReportFields.CHECK_SUCCESS, 0);

      // Tell the callback about the updates
      this._callback.onCheckComplete(event.target, updates, updates.length);
    }
    catch (e) {
      LOG("Checker:onLoad - there was a problem checking for updates. " +
          "Exception: " + e);
      var request = event.target;
      var status = this._getChannelStatus(request);
      LOG("Checker:onLoad - request.status: " + status);
      var update = new Update(null);
      update.errorCode = status;
      update.statusText = getStatusTextFromCode(status, 404);

      if (this._isHttpStatusCode(status)) {
        update.errorCode = HTTP_ERROR_OFFSET + status;
      }
      if (e.result == Cr.NS_ERROR_ILLEGAL_VALUE) {
        update.errorCode = updates[0] ? CERT_ATTR_CHECK_FAILED_HAS_UPDATE
                                      : CERT_ATTR_CHECK_FAILED_NO_UPDATE;
      }

      recordInHealthReport(UpdaterHealthReportFields.CHECK_FAILED, update.errorCode);

      this._callback.onError(request, update);
    }

    this._callback = null;
    this._request = null;
  },

  /**
   * There was an error of some kind during the XMLHttpRequest
   * @param   event
   *          The nsIDOMEvent for the error
   */
  onError: function UC_onError(event) {
    var request = event.target;
    var status = this._getChannelStatus(request);
    LOG("Checker:onError - request.status: " + status);

    // If we can't find an error string specific to this status code,
    // just use the 200 message from above, which means everything
    // "looks" fine but there was probably an XML error or a bogus file.
    var update = new Update(null);
    update.errorCode = status;
    update.statusText = getStatusTextFromCode(status, 200);

    if (status == Cr.NS_ERROR_OFFLINE) {
      // We use a separate constant here because nsIUpdate.errorCode is signed
      update.errorCode = NETWORK_ERROR_OFFLINE;
    } else if (this._isHttpStatusCode(status)) {
      update.errorCode = HTTP_ERROR_OFFSET + status;
    }

    recordInHealthReport(UpdaterHealthReportFields.CHECK_FAILED, update.errorCode);

    this._callback.onError(request, update);

    this._request = null;
  },

  /**
   * Whether or not we are allowed to do update checking.
   */
  _enabled: true,
  get enabled() {
    if (!gMetroUpdatesEnabled) {
      return false;
    }

    return getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) &&
           gCanCheckForUpdates && hasUpdateMutex() && this._enabled;
  },

  /**
   * See nsIUpdateService.idl
   */
  stopChecking: function UC_stopChecking(duration) {
    // Always stop the current check
    if (this._request)
      this._request.abort();

    switch (duration) {
    case Ci.nsIUpdateChecker.CURRENT_SESSION:
      this._enabled = false;
      break;
    case Ci.nsIUpdateChecker.ANY_CHECKS:
      this._enabled = false;
      Services.prefs.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
      break;
    }

    this._callback = null;
  },

  classID: Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateChecker])
};

/**
 * Manages the download of updates
 * @param   background
 *          Whether or not this downloader is operating in background
 *          update mode.
 * @param   updateService
 *          The update service that created this downloader.
 * @constructor
 */
function Downloader(background, updateService) {
  LOG("Creating Downloader");
  this.background = background;
  this.updateService = updateService;
}
Downloader.prototype = {
  /**
   * The nsIUpdatePatch that we are downloading
   */
  _patch: null,

  /**
   * The nsIUpdate that we are downloading
   */
  _update: null,

  /**
   * The nsIIncrementalDownload object handling the download
   */
  _request: null,

  /**
   * Whether or not the update being downloaded is a complete replacement of
   * the user's existing installation or a patch representing the difference
   * between the new version and the previous version.
   */
  isCompleteUpdate: null,

  /**
   * Cancels the active download.
   */
  cancel: function Downloader_cancel(cancelError) {
    LOG("Downloader: cancel");
    if (cancelError === undefined) {
      cancelError = Cr.NS_BINDING_ABORTED;
    }
    if (this._request && this._request instanceof Ci.nsIRequest) {
      this._request.cancel(cancelError);
    }
    releaseSDCardMountLock();
  },

  /**
   * Whether or not a patch has been downloaded and staged for installation.
   */
  get patchIsStaged() {
    var readState = readStatusFile(getUpdatesDir());
    // Note that if we decide to download and apply new updates after another
    // update has been successfully applied in the background, we need to stop
    // checking for the APPLIED state here.
    return readState == STATE_PENDING || readState == STATE_APPLIED;
  },

  /**
   * Verify the downloaded file.  We assume that the download is complete at
   * this point.
   */
  _verifyDownload: function Downloader__verifyDownload() {
    LOG("Downloader:_verifyDownload called");
    if (!this._request)
      return false;

    var destination = this._request.destination;

    // Ensure that the file size matches the expected file size.
    if (destination.fileSize != this._patch.size) {
      LOG("Downloader:_verifyDownload downloaded size != expected size.");
      return false;
    }

    LOG("Downloader:_verifyDownload downloaded size == expected size.");
    var fileStream = Cc["@mozilla.org/network/file-input-stream;1"].
                     createInstance(Ci.nsIFileInputStream);
    fileStream.init(destination, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0);

    try {
      var hash = Cc["@mozilla.org/security/hash;1"].
                 createInstance(Ci.nsICryptoHash);
      var hashFunction = Ci.nsICryptoHash[this._patch.hashFunction.toUpperCase()];
      if (hashFunction == undefined)
        throw Cr.NS_ERROR_UNEXPECTED;
      hash.init(hashFunction);
      hash.updateFromStream(fileStream, -1);
      // NOTE: For now, we assume that the format of _patch.hashValue is hex
      // encoded binary (such as what is typically output by programs like
      // sha1sum).  In the future, this may change to base64 depending on how
      // we choose to compute these hashes.
      digest = binaryToHex(hash.finish(false));
    } catch (e) {
      LOG("Downloader:_verifyDownload - failed to compute hash of the " +
          "downloaded update archive");
      digest = "";
    }

    fileStream.close();

    if (digest == this._patch.hashValue.toLowerCase()) {
      LOG("Downloader:_verifyDownload hashes match.");
      return true;
    }

    LOG("Downloader:_verifyDownload hashes do not match. ");
    return false;
  },

  /**
   * Select the patch to use given the current state of updateDir and the given
   * set of update patches.
   * @param   update
   *          A nsIUpdate object to select a patch from
   * @param   updateDir
   *          A nsIFile representing the update directory
   * @return  A nsIUpdatePatch object to download
   */
  _selectPatch: function Downloader__selectPatch(update, updateDir) {
    // Given an update to download, we will always try to download the patch
    // for a partial update over the patch for a full update.

    /**
     * Return the first UpdatePatch with the given type.
     * @param   type
     *          The type of the patch ("complete" or "partial")
     * @return  A nsIUpdatePatch object matching the type specified
     */
    function getPatchOfType(type) {
      for (var i = 0; i < update.patchCount; ++i) {
        var patch = update.getPatchAt(i);
        if (patch && patch.type == type)
          return patch;
      }
      return null;
    }

    // Look to see if any of the patches in the Update object has been
    // pre-selected for download, otherwise we must figure out which one
    // to select ourselves.
    var selectedPatch = update.selectedPatch;

    var state = readStatusFile(updateDir);

    // If this is a patch that we know about, then select it.  If it is a patch
    // that we do not know about, then remove it and use our default logic.
    var useComplete = false;
    if (selectedPatch) {
      LOG("Downloader:_selectPatch - found existing patch with state: " +
          state);
      switch (state) {
      case STATE_DOWNLOADING:
        LOG("Downloader:_selectPatch - resuming download");
        return selectedPatch;
#ifdef MOZ_WIDGET_GONK
      case STATE_PENDING:
      case STATE_APPLYING:
        LOG("Downloader:_selectPatch - resuming interrupted apply");
        return selectedPatch;
      case STATE_APPLIED:
        LOG("Downloader:_selectPatch - already downloaded and staged");
        return null;
#else
      case STATE_PENDING:
        LOG("Downloader:_selectPatch - already downloaded and staged");
        return null;
#endif
      default:
        // Something went wrong when we tried to apply the previous patch.
        // Try the complete patch next time.
        if (update && selectedPatch.type == "partial") {
          useComplete = true;
        } else {
          // This is a pretty fatal error.  Just bail.
          LOG("Downloader:_selectPatch - failed to apply complete patch!");
          writeStatusFile(updateDir, STATE_NONE);
          writeVersionFile(getUpdatesDir(), null);
          return null;
        }
      }

      selectedPatch = null;
    }

    // If we were not able to discover an update from a previous download, we
    // select the best patch from the given set.
    var partialPatch = getPatchOfType("partial");
    if (!useComplete)
      selectedPatch = partialPatch;
    if (!selectedPatch) {
      if (partialPatch)
        partialPatch.selected = false;
      selectedPatch = getPatchOfType("complete");
    }

    // Restore the updateDir since we may have deleted it.
    updateDir = getUpdatesDir();

    // if update only contains a partial patch, selectedPatch == null here if
    // the partial patch has been attempted and fails and we're trying to get a
    // complete patch
    if (selectedPatch)
      selectedPatch.selected = true;

    update.isCompleteUpdate = useComplete;

    // Reset the Active Update object on the Update Manager and flush the
    // Active Update DB.
    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);
    um.activeUpdate = update;

    return selectedPatch;
  },

  /**
   * Whether or not we are currently downloading something.
   */
  get isBusy() {
    return this._request != null;
  },

  /**
   * Get the nsIFile to use for downloading the active update's selected patch
   */
  _getUpdateArchiveFile: function Downloader__getUpdateArchiveFile() {
    var updateArchive;
#ifdef USE_UPDATE_ARCHIVE_DIR
    try {
      updateArchive = FileUtils.getDir(KEY_UPDATE_ARCHIVE_DIR, [], true);
    } catch (e) {
      return null;
    }
#else
    updateArchive = getUpdatesDir().clone();
#endif

    updateArchive.append(FILE_UPDATE_ARCHIVE);
    return updateArchive;
  },

  /**
   * Download and stage the given update.
   * @param   update
   *          A nsIUpdate object to download a patch for. Cannot be null.
   */
  downloadUpdate: function Downloader_downloadUpdate(update) {
    LOG("UpdateService:_downloadUpdate");
    if (!update)
      throw Cr.NS_ERROR_NULL_POINTER;

    var updateDir = getUpdatesDir();

    this._update = update;

    // This function may return null, which indicates that there are no patches
    // to download.
    this._patch = this._selectPatch(update, updateDir);
    if (!this._patch) {
      LOG("Downloader:downloadUpdate - no patch to download");
      return readStatusFile(updateDir);
    }
    this.isCompleteUpdate = this._patch.type == "complete";

    recordInHealthReport(
      this.isCompleteUpdate ? UpdaterHealthReportFields.COMPLETE_START :
                              UpdaterHealthReportFields.PARTIAL_START, 0);

    var patchFile = null;

#ifdef MOZ_WIDGET_GONK
    let status = readStatusFile(updateDir);
    if (isInterruptedUpdate(status)) {
      LOG("Downloader:downloadUpdate - interruptted update");
      // The update was interrupted. Try to locate the existing patch file.
      // For an interrupted download, this allows a resume rather than a
      // re-download.
      patchFile = getFileFromUpdateLink(updateDir);
      if (!patchFile) {
        // No link file. We'll just assume that the update.mar is in the
        // update directory.
        patchFile = updateDir.clone();
        patchFile.append(FILE_UPDATE_ARCHIVE);
      }
      if (patchFile.exists()) {
        LOG("Downloader:downloadUpdate - resuming with patchFile " + patchFile.path);
        if (patchFile.fileSize == this._patch.size) {
          LOG("Downloader:downloadUpdate - patchFile appears to be fully downloaded");
          // Bump the status along so that we don't try to redownload again.
          status = STATE_PENDING;
        }
      } else {
        LOG("Downloader:downloadUpdate - patchFile " + patchFile.path +
            " doesn't exist - performing full download");
        // The patchfile doesn't exist, we might as well treat this like
        // a new download.
        patchFile = null;
      }
      if (patchFile && (status != STATE_DOWNLOADING)) {
        // It looks like the patch was downloaded, but got interrupted while it
        // was being verified or applied. So we'll fake the downloading portion.

        writeStatusFile(updateDir, STATE_PENDING);

        // Since the code expects the onStopRequest callback to happen
        // asynchronously (And you have to call AUS_addDownloadListener
        // after calling AUS_downloadUpdate) we need to defer this.

        this._downloadTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
        this._downloadTimer.initWithCallback(function() {
          this._downloadTimer = null;
          // Send a fake onStopRequest. Filling in the destination allows
          // _verifyDownload to work, and then the update will be applied.
          this._request = {destination: patchFile};
          this.onStopRequest(this._request, null, Cr.NS_OK);
        }.bind(this), 0, Ci.nsITimer.TYPE_ONE_SHOT);

        // Returning STATE_DOWNLOADING makes UpdatePrompt think we're
        // downloading. The onStopRequest that we spoofed above will make it
        // look like the download finished.
        return STATE_DOWNLOADING;
      }
    }
#endif
    if (!patchFile) {
      // Find a place to put the patchfile that we're going to download.
      patchFile = this._getUpdateArchiveFile();
    }
    if (!patchFile) {
      return STATE_NONE;
    }

#ifdef MOZ_WIDGET_GONK
    if (patchFile.path.indexOf(updateDir.path) != 0) {
      // The patchFile is in a directory which is different from the
      // updateDir, create a link file.
      writeLinkFile(updateDir, patchFile);

      if (!isInterruptedUpdate(status) && patchFile.exists()) {
        // Remove stale patchFile
        patchFile.remove(false);
      }
    }
#endif

    var uri = Services.io.newURI(this._patch.URL, null, null);

    this._request = Cc["@mozilla.org/network/incremental-download;1"].
                    createInstance(Ci.nsIIncrementalDownload);

    LOG("Downloader:downloadUpdate - downloading from " + uri.spec + " to " +
        patchFile.path);
    var interval = this.background ? getPref("getIntPref",
                                             PREF_APP_UPDATE_BACKGROUND_INTERVAL,
                                             DOWNLOAD_BACKGROUND_INTERVAL)
                                   : DOWNLOAD_FOREGROUND_INTERVAL;
    this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
    this._request.start(this, null);

    writeStatusFile(updateDir, STATE_DOWNLOADING);
    this._patch.QueryInterface(Ci.nsIWritablePropertyBag);
    this._patch.state = STATE_DOWNLOADING;
    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);
    um.saveUpdates();
    return STATE_DOWNLOADING;
  },

  /**
   * An array of download listeners to notify when we receive
   * nsIRequestObserver or nsIProgressEventSink method calls.
   */
  _listeners: [],

  /**
   * Adds a listener to the download process
   * @param   listener
   *          A download listener, implementing nsIRequestObserver and
   *          nsIProgressEventSink
   */
  addDownloadListener: function Downloader_addDownloadListener(listener) {
    for (var i = 0; i < this._listeners.length; ++i) {
      if (this._listeners[i] == listener)
        return;
    }
    this._listeners.push(listener);
  },

  /**
   * Removes a download listener
   * @param   listener
   *          The listener to remove.
   */
  removeDownloadListener: function Downloader_removeDownloadListener(listener) {
    for (var i = 0; i < this._listeners.length; ++i) {
      if (this._listeners[i] == listener) {
        this._listeners.splice(i, 1);
        return;
      }
    }
  },

  /**
   * When the async request begins
   * @param   request
   *          The nsIRequest object for the transfer
   * @param   context
   *          Additional data
   */
  onStartRequest: function Downloader_onStartRequest(request, context) {
    if (request instanceof Ci.nsIIncrementalDownload)
      LOG("Downloader:onStartRequest - original URI spec: " + request.URI.spec +
          ", final URI spec: " + request.finalURI.spec);
    // Always set finalURL in onStartRequest since it can change.
    this._patch.finalURL = request.finalURI.spec;
    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);
    um.saveUpdates();

    var listeners = this._listeners.concat();
    var listenerCount = listeners.length;
    for (var i = 0; i < listenerCount; ++i)
      listeners[i].onStartRequest(request, context);
  },

  /**
   * When new data has been downloaded
   * @param   request
   *          The nsIRequest object for the transfer
   * @param   context
   *          Additional data
   * @param   progress
   *          The current number of bytes transferred
   * @param   maxProgress
   *          The total number of bytes that must be transferred
   */
  onProgress: function Downloader_onProgress(request, context, progress,
                                             maxProgress) {
    LOG("Downloader:onProgress - progress: " + progress + "/" + maxProgress);

    if (progress > this._patch.size) {
      LOG("Downloader:onProgress - progress: " + progress +
          " is higher than patch size: " + this._patch.size);
      // It's important that we use a different code than
      // NS_ERROR_CORRUPTED_CONTENT so that tests can verify the difference
      // between a hash error and a wrong download error.
      this.cancel(Cr.NS_ERROR_UNEXPECTED);
      return;
    }

    if (maxProgress != this._patch.size) {
      LOG("Downloader:onProgress - maxProgress: " + maxProgress +
          " is not equal to expectd patch size: " + this._patch.size);
      // It's important that we use a different code than
      // NS_ERROR_CORRUPTED_CONTENT so that tests can verify the difference
      // between a hash error and a wrong download error.
      this.cancel(Cr.NS_ERROR_UNEXPECTED);
      return;
    }

    var listeners = this._listeners.concat();
    var listenerCount = listeners.length;
    for (var i = 0; i < listenerCount; ++i) {
      var listener = listeners[i];
      if (listener instanceof Ci.nsIProgressEventSink)
        listener.onProgress(request, context, progress, maxProgress);
    }
    this.updateService._consecutiveSocketErrors = 0;
  },

  /**
   * When we have new status text
   * @param   request
   *          The nsIRequest object for the transfer
   * @param   context
   *          Additional data
   * @param   status
   *          A status code
   * @param   statusText
   *          Human readable version of |status|
   */
  onStatus: function Downloader_onStatus(request, context, status, statusText) {
    LOG("Downloader:onStatus - status: " + status + ", statusText: " +
        statusText);

    var listeners = this._listeners.concat();
    var listenerCount = listeners.length;
    for (var i = 0; i < listenerCount; ++i) {
      var listener = listeners[i];
      if (listener instanceof Ci.nsIProgressEventSink)
        listener.onStatus(request, context, status, statusText);
    }
  },

  /**
   * When data transfer ceases
   * @param   request
   *          The nsIRequest object for the transfer
   * @param   context
   *          Additional data
   * @param   status
   *          Status code containing the reason for the cessation.
   */
  onStopRequest: function  Downloader_onStopRequest(request, context, status) {
    if (request instanceof Ci.nsIIncrementalDownload)
      LOG("Downloader:onStopRequest - original URI spec: " + request.URI.spec +
          ", final URI spec: " + request.finalURI.spec + ", status: " + status);

    // XXX ehsan shouldShowPrompt should always be false here.
    // But what happens when there is already a UI showing?
    var state = this._patch.state;
    var shouldShowPrompt = false;
    var shouldRegisterOnlineObserver = false;
    var shouldRetrySoon = false;
    var deleteActiveUpdate = false;
    var retryTimeout = getPref("getIntPref", PREF_APP_UPDATE_RETRY_TIMEOUT,
                               DEFAULT_UPDATE_RETRY_TIMEOUT);
    var maxFail = getPref("getIntPref", PREF_APP_UPDATE_SOCKET_ERRORS,
                          DEFAULT_SOCKET_MAX_ERRORS);
    LOG("Downloader:onStopRequest - status: " + status + ", " +
        "current fail: " + this.updateService._consecutiveSocketErrors + ", " +
        "max fail: " + maxFail + ", " + "retryTimeout: " + retryTimeout);
    if (Components.isSuccessCode(status)) {
      recordInHealthReport(
        this.isCompleteUpdate ? UpdaterHealthReportFields.COMPLETE_SUCCESS :
                                UpdaterHealthReportFields.PARTIAL_SUCCESS, 0);

      if (this._verifyDownload()) {
        state = STATE_PENDING;
        if (this.background) {
          shouldShowPrompt = !getCanStageUpdates();
        }

        // Tell the updater.exe we're ready to apply.
        writeStatusFile(getUpdatesDir(), state);
        writeVersionFile(getUpdatesDir(), this._update.appVersion);
        this._update.installDate = (new Date()).getTime();
        this._update.statusText = gUpdateBundle.GetStringFromName("installPending");
      }
      else {
        LOG("Downloader:onStopRequest - download verification failed");
        state = STATE_DOWNLOAD_FAILED;
        status = Cr.NS_ERROR_CORRUPTED_CONTENT;

        // Yes, this code is a string.
        const vfCode = "verification_failed";
        var message = getStatusTextFromCode(vfCode, vfCode);
        this._update.statusText = message;

        if (this._update.isCompleteUpdate || this._update.patchCount != 2)
          deleteActiveUpdate = true;

        // Destroy the updates directory, since we're done with it.
        cleanUpUpdatesDir();
      }
    } else {
      recordInHealthReport(UpdaterHealthReportFields.FAILED, status);

      if (status == Cr.NS_ERROR_OFFLINE) {
        // Register an online observer to try again.
        // The online observer will continue the incremental download by
        // calling downloadUpdate on the active update which continues
        // downloading the file from where it was.
        LOG("Downloader:onStopRequest - offline, register online observer: true");
        shouldRegisterOnlineObserver = true;
        deleteActiveUpdate = false;
      // Each of NS_ERROR_NET_TIMEOUT, ERROR_CONNECTION_REFUSED, and
      // NS_ERROR_NET_RESET can be returned when disconnecting the internet while
      // a download of a MAR is in progress.  There may be others but I have not
      // encountered them during testing.
      } else if ((status == Cr.NS_ERROR_NET_TIMEOUT ||
                  status == Cr.NS_ERROR_CONNECTION_REFUSED ||
                  status == Cr.NS_ERROR_NET_RESET) &&
                 this.updateService._consecutiveSocketErrors < maxFail) {
        LOG("Downloader:onStopRequest - socket error, shouldRetrySoon: true");
        shouldRetrySoon = true;
        deleteActiveUpdate = false;
      } else if (status != Cr.NS_BINDING_ABORTED &&
                 status != Cr.NS_ERROR_ABORT &&
                 status != Cr.NS_ERROR_DOCUMENT_NOT_CACHED) {
        LOG("Downloader:onStopRequest - non-verification failure");
        // Some sort of other failure, log this in the |statusText| property
        state = STATE_DOWNLOAD_FAILED;

        // XXXben - if |request| (The Incremental Download) provided a means
        // for accessing the http channel we could do more here.

        this._update.statusText = getStatusTextFromCode(status,
                                                        Cr.NS_BINDING_FAILED);

#ifdef MOZ_WIDGET_GONK
        // bug891009: On FirefoxOS, manaully retry OTA download will reuse
        // the Update object. We need to remove selected patch so that download
        // can be triggered again successfully.
        this._update.selectedPatch.selected = false;
#endif

        // Destroy the updates directory, since we're done with it.
        cleanUpUpdatesDir();

        deleteActiveUpdate = true;
      }
    }
    LOG("Downloader:onStopRequest - setting state to: " + state);
    this._patch.state = state;
    var um = Cc["@mozilla.org/updates/update-manager;1"].
             getService(Ci.nsIUpdateManager);
    if (deleteActiveUpdate) {
      this._update.installDate = (new Date()).getTime();
      um.activeUpdate = null;
    }
    else {
      if (um.activeUpdate)
        um.activeUpdate.state = state;
    }
    um.saveUpdates();

    // Only notify listeners about the stopped state if we
    // aren't handling an internal retry.
    if (!shouldRetrySoon && !shouldRegisterOnlineObserver) {
      var listeners = this._listeners.concat();
      var listenerCount = listeners.length;
      for (var i = 0; i < listenerCount; ++i) {
        listeners[i].onStopRequest(request, context, status);
      }
    }

    this._request = null;

    if (state == STATE_DOWNLOAD_FAILED) {
      var allFailed = true;
      // Check if there is a complete update patch that can be downloaded.
      if (!this._update.isCompleteUpdate && this._update.patchCount == 2) {
        LOG("Downloader:onStopRequest - verification of patch failed, " +
            "downloading complete update patch");
        this._update.isCompleteUpdate = true;
        let updateStatus = this.downloadUpdate(this._update);

        if (updateStatus == STATE_NONE) {
          cleanupActiveUpdate();
        } else {
          allFailed = false;
        }
      }

      if (allFailed) {
        LOG("Downloader:onStopRequest - all update patch downloads failed");
        // If the update UI is not open (e.g. the user closed the window while
        // downloading) and if at any point this was a foreground download
        // notify the user about the error. If the update was a background
        // update there is no notification since the user won't be expecting it.
        if (!Services.wm.getMostRecentWindow(UPDATE_WINDOW_NAME)) {
          try {
            this._update.QueryInterface(Ci.nsIWritablePropertyBag);
            var fgdl = this._update.getProperty("foregroundDownload");
          }
          catch (e) {
          }

          if (fgdl == "true") {
            var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                           createInstance(Ci.nsIUpdatePrompt);
            prompter.showUpdateError(this._update);
          }
        }

#ifdef MOZ_WIDGET_GONK
        // We always forward errors in B2G, since Gaia controls the update UI
        var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                       createInstance(Ci.nsIUpdatePrompt);
        prompter.showUpdateError(this._update);
#endif

        // Prevent leaking the update object (bug 454964).
        this._update = null;
      }
      // A complete download has been initiated or the failure was handled.
      return;
    }

    if (state == STATE_PENDING) {
      if (getCanStageUpdates()) {
        LOG("Downloader:onStopRequest - attempting to stage update: " +
            this._update.name);

        // Initiate the update in the background
        try {
          Cc["@mozilla.org/updates/update-processor;1"].
            createInstance(Ci.nsIUpdateProcessor).
            processUpdate(this._update);
        } catch (e) {
          // Fail gracefully in case the application does not support the update
          // processor service.
          LOG("Downloader:onStopRequest - failed to stage update. Exception: " +
              e);
          if (this.background) {
            shouldShowPrompt = true;
          }
        }
      }
    }

    // Do this after *everything* else, since it will likely cause the app
    // to shut down.
    if (shouldShowPrompt) {
      // Notify the user that an update has been downloaded and is ready for
      // installation (i.e. that they should restart the application). We do
      // not notify on failed update attempts.
      var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
                     createInstance(Ci.nsIUpdatePrompt);
      prompter.showUpdateDownloaded(this._update, true);
    }

    if (shouldRegisterOnlineObserver) {
      LOG("Downloader:onStopRequest - Registering online observer");
      this.updateService._registerOnlineObserver();
    } else if (shouldRetrySoon) {
      LOG("Downloader:onStopRequest - Retrying soon");
      this.updateService._consecutiveSocketErrors++;
      if (this.updateService._retryTimer) {
        this.updateService._retryTimer.cancel();
      }
      this.updateService._retryTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
      this.updateService._retryTimer.initWithCallback(function() {
        this._attemptResume();
      }.bind(this.updateService), retryTimeout, Ci.nsITimer.TYPE_ONE_SHOT);
    } else {
      // Prevent leaking the update object (bug 454964)
      this._update = null;
    }
  },

  /**
   * See nsIInterfaceRequestor.idl
   */
  getInterface: function Downloader_getInterface(iid) {
    // The network request may require proxy authentication, so provide the
    // default nsIAuthPrompt if requested.
    if (iid.equals(Ci.nsIAuthPrompt)) {
      var prompt = Cc["@mozilla.org/network/default-auth-prompt;1"].
                   createInstance();
      return prompt.QueryInterface(iid);
    }
    throw Cr.NS_NOINTERFACE;
  },

  QueryInterface: XPCOMUtils.generateQI([Ci.nsIRequestObserver,
                                         Ci.nsIProgressEventSink,
                                         Ci.nsIInterfaceRequestor])
};

/**
 * UpdatePrompt
 * An object which can prompt the user with information about updates, request
 * action, etc. Embedding clients can override this component with one that
 * invokes a native front end.
 * @constructor
 */
function UpdatePrompt() {
}
UpdatePrompt.prototype = {
  /**
   * See nsIUpdateService.idl
   */
  checkForUpdates: function UP_checkForUpdates() {
    if (this._getAltUpdateWindow())
      return;

    this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, UPDATE_WINDOW_NAME,
                 null, null);
  },

  /**
   * See nsIUpdateService.idl
   */
  showUpdateAvailable: function UP_showUpdateAvailable(update) {
    if (getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false) ||
        this._getUpdateWindow() || this._getAltUpdateWindow())
      return;

    var stringsPrefix = "updateAvailable_" + update.type + ".";
    var title = gUpdateBundle.formatStringFromName(stringsPrefix + "title",
                                                   [update.name], 1);
    var text = gUpdateBundle.GetStringFromName(stringsPrefix + "text");
    var imageUrl = "";
    this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
                           UPDATE_WINDOW_NAME, "updatesavailable", update,
                           title, text, imageUrl);
  },

  /**
   * See nsIUpdateService.idl
   */
  showUpdateDownloaded: function UP_showUpdateDownloaded(update, background) {
    if (this._getAltUpdateWindow())
      return;

    if (background) {
      if (getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false))
        return;

      var stringsPrefix = "updateDownloaded_" + update.type + ".";
      var title = gUpdateBundle.formatStringFromName(stringsPrefix + "title",
                                                     [update.name], 1);
      var text = gUpdateBundle.GetStringFromName(stringsPrefix + "text");
      var imageUrl = "";
      this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
                              UPDATE_WINDOW_NAME, "finishedBackground", update,
                              title, text, imageUrl);
    } else {
      this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null,
                   UPDATE_WINDOW_NAME, "finishedBackground", update);
    }
  },

  /**
   * See nsIUpdateService.idl
   */
  showUpdateInstalled: function UP_showUpdateInstalled() {
    if (getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false) ||
        !getPref("getBoolPref", PREF_APP_UPDATE_SHOW_INSTALLED_UI, false) ||
        this._getUpdateWindow())
      return;

    var page = "installed";
    var win = this._getUpdateWindow();
    if (win) {
      if (page && "setCurrentPage" in win)
        win.setCurrentPage(page);
      win.focus();
    }
    else {
      var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
      var arg = Cc["@mozilla.org/supports-string;1"].
                createInstance(Ci.nsISupportsString);
      arg.data = page;
      Services.ww.openWindow(null, URI_UPDATE_PROMPT_DIALOG, null, openFeatures, arg);
    }
  },

  /**
   * See nsIUpdateService.idl
   */
  showUpdateError: function UP_showUpdateError(update) {
    if (getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false) ||
        this._getAltUpdateWindow())
      return;

    // In some cases, we want to just show a simple alert dialog:
    if (update.state == STATE_FAILED &&
        (update.errorCode == WRITE_ERROR ||
         update.errorCode == WRITE_ERROR_ACCESS_DENIED ||
         update.errorCode == WRITE_ERROR_SHARING_VIOLATION_SIGNALED ||
         update.errorCode == WRITE_ERROR_SHARING_VIOLATION_NOPROCESSFORPID ||
         update.errorCode == WRITE_ERROR_SHARING_VIOLATION_NOPID ||
         update.errorCode == WRITE_ERROR_CALLBACK_APP ||
         update.errorCode == FILESYSTEM_MOUNT_READWRITE_ERROR ||
         update.errorCode == FOTA_GENERAL_ERROR ||
         update.errorCode == FOTA_FILE_OPERATION_ERROR ||
         update.errorCode == FOTA_RECOVERY_ERROR ||
         update.errorCode == FOTA_UNKNOWN_ERROR)) {
      var title = gUpdateBundle.GetStringFromName("updaterIOErrorTitle");
      var text = gUpdateBundle.formatStringFromName("updaterIOErrorMsg",
                                                    [Services.appinfo.name,
                                                     Services.appinfo.name], 2);
      Services.ww.getNewPrompter(null).alert(title, text);
      return;
    }

    if (update.errorCode == CERT_ATTR_CHECK_FAILED_NO_UPDATE ||
        update.errorCode == CERT_ATTR_CHECK_FAILED_HAS_UPDATE ||
        update.errorCode == BACKGROUNDCHECK_MULTIPLE_FAILURES) {
      this._showUIWhenIdle(null, URI_UPDATE_PROMPT_DIALOG, null,
                           UPDATE_WINDOW_NAME, null, update);
      return;
    }

    this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, UPDATE_WINDOW_NAME,
                 "errors", update);
  },

  /**
   * See nsIUpdateService.idl
   */
  showUpdateHistory: function UP_showUpdateHistory(parent) {
    this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes",
                 "Update:History", null, null);
  },

  /**
   * Returns the update window if present.
   */
  _getUpdateWindow: function UP__getUpdateWindow() {
    return Services.wm.getMostRecentWindow(UPDATE_WINDOW_NAME);
  },

  /**
   * Returns an alternative update window if present. When a window with this
   * windowtype is open the application update service won't open the normal
   * application update user interface window.
   */
  _getAltUpdateWindow: function UP__getAltUpdateWindow() {
    let windowType = getPref("getCharPref", PREF_APP_UPDATE_ALTWINDOWTYPE, null);
    if (!windowType)
      return null;
    return Services.wm.getMostRecentWindow(windowType);
  },

  /**
   * Initiate a less obtrusive UI, starting with a non-modal notification alert
   * @param   parent
   *          A parent window, can be null
   * @param   uri
   *          The URI string of the dialog to show
   * @param   name
   *          The Window Name of the dialog to show, in case it is already open
   *          and can merely be focused
   * @param   page
   *          The page of the wizard to be displayed, if one is already open.
   * @param   update
   *          An update to pass to the UI in the window arguments.
   *          Can be null
   * @param   title
   *          The title for the notification alert.
   * @param   text
   *          The contents of the notification alert.
   * @param   imageUrl
   *          A URL identifying the image to put in the notification alert.
   */
  _showUnobtrusiveUI: function UP__showUnobUI(parent, uri, features, name, page,
                                              update, title, text, imageUrl) {
    var observer = {
      updatePrompt: this,
      service: null,
      timer: null,
      notify: function () {
        // the user hasn't restarted yet => prompt when idle
        this.service.removeObserver(this, "quit-application");
        // If the update window is already open skip showing the UI
        if (this.updatePrompt._getUpdateWindow())
          return;
        this.updatePrompt._showUIWhenIdle(parent, uri, features, name, page, update);
      },
      observe: function (aSubject, aTopic, aData) {
        switch (aTopic) {
          case "alertclickcallback":
            this.updatePrompt._showUI(parent, uri, features, name, page, update);
            // fall thru
          case "quit-application":
            if (this.timer)
              this.timer.cancel();
            this.service.removeObserver(this, "quit-application");
            break;
        }
      }
    };

    // bug 534090 - show the UI for update available notifications when the
    // the system has been idle for at least IDLE_TIME without displaying an
    // alert notification.
    if (page == "updatesavailable") {
      var idleService = Cc["@mozilla.org/widget/idleservice;1"].
                        getService(Ci.nsIIdleService);

      const IDLE_TIME = getPref("getIntPref", PREF_APP_UPDATE_IDLETIME, 60);
      if (idleService.idleTime / 1000 >= IDLE_TIME) {
        this._showUI(parent, uri, features, name, page, update);
        return;
      }
    }

    try {
      var notifier = Cc["@mozilla.org/alerts-service;1"].
                     getService(Ci.nsIAlertsService);
      notifier.showAlertNotification(imageUrl, title, text, true, "", observer);
    }
    catch (e) {
      // Failed to retrieve alerts service, platform unsupported
      this._showUIWhenIdle(parent, uri, features, name, page, update);
      return;
    }

    observer.service = Services.obs;
    observer.service.addObserver(observer, "quit-application", false);

    // bug 534090 - show the UI when idle for update available notifications.
    if (page == "updatesavailable") {
      this._showUIWhenIdle(parent, uri, features, name, page, update);
      return;
    }

    // Give the user x seconds to react before prompting as defined by
    // promptWaitTime
    observer.timer = Cc["@mozilla.org/timer;1"].
                     createInstance(Ci.nsITimer);
    observer.timer.initWithCallback(observer, update.promptWaitTime * 1000,
                                    observer.timer.TYPE_ONE_SHOT);
  },

  /**
   * Show the UI when the user was idle
   * @param   parent
   *          A parent window, can be null
   * @param   uri
   *          The URI string of the dialog to show
   * @param   name
   *          The Window Name of the dialog to show, in case it is already open
   *          and can merely be focused
   * @param   page
   *          The page of the wizard to be displayed, if one is already open.
   * @param   update
   *          An update to pass to the UI in the window arguments.
   *          Can be null
   */
  _showUIWhenIdle: function UP__showUIWhenIdle(parent, uri, features, name,
                                               page, update) {
    var idleService = Cc["@mozilla.org/widget/idleservice;1"].
                      getService(Ci.nsIIdleService);

    const IDLE_TIME = getPref("getIntPref", PREF_APP_UPDATE_IDLETIME, 60);
    if (idleService.idleTime / 1000 >= IDLE_TIME) {
      this._showUI(parent, uri, features, name, page, update);
    } else {
      var observer = {
        updatePrompt: this,
        observe: function (aSubject, aTopic, aData) {
          switch (aTopic) {
            case "idle":
              // If the update window is already open skip showing the UI
              if (!this.updatePrompt._getUpdateWindow())
                this.updatePrompt._showUI(parent, uri, features, name, page, update);
              // fall thru
            case "quit-application":
              idleService.removeIdleObserver(this, IDLE_TIME);
              Services.obs.removeObserver(this, "quit-application");
              break;
          }
        }
      };
      idleService.addIdleObserver(observer, IDLE_TIME);
      Services.obs.addObserver(observer, "quit-application", false);
    }
  },

  /**
   * Show the Update Checking UI
   * @param   parent
   *          A parent window, can be null
   * @param   uri
   *          The URI string of the dialog to show
   * @param   name
   *          The Window Name of the dialog to show, in case it is already open
   *          and can merely be focused
   * @param   page
   *          The page of the wizard to be displayed, if one is already open.
   * @param   update
   *          An update to pass to the UI in the window arguments.
   *          Can be null
   */
  _showUI: function UP__showUI(parent, uri, features, name, page, update) {
    var ary = null;
    if (update) {
      ary = Cc["@mozilla.org/supports-array;1"].
            createInstance(Ci.nsISupportsArray);
      ary.AppendElement(update);
    }

    var win = this._getUpdateWindow();
    if (win) {
      if (page && "setCurrentPage" in win)
        win.setCurrentPage(page);
      win.focus();
    }
    else {
      var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
      if (features)
        openFeatures += "," + features;
      Services.ww.openWindow(parent, uri, "", openFeatures, ary);
    }
  },

  classDescription: "Update Prompt",
  contractID: "@mozilla.org/updates/update-prompt;1",
  classID: Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdatePrompt])
};

var components = [UpdateService, Checker, UpdatePrompt, UpdateManager];
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(components);

#if 0
/**
 * Logs a message and stack trace to the console.
 * @param   string
 *          The string to write to the console.
 */
function STACK(string) {
  dump("*** " + string + "\n");
  stackTrace(arguments.callee.caller.arguments, -1);
}

function stackTraceFunctionFormat(aFunctionName) {
  var classDelimiter = aFunctionName.indexOf("_");
  var className = aFunctionName.substr(0, classDelimiter);
  if (!className)
    className = "<global>";
  var functionName = aFunctionName.substr(classDelimiter + 1, aFunctionName.length);
  if (!functionName)
    functionName = "<anonymous>";
  return className + "::" + functionName;
}

function stackTraceArgumentsFormat(aArguments) {
  arglist = "";
  for (var i = 0; i < aArguments.length; i++) {
    arglist += aArguments[i];
    if (i < aArguments.length - 1)
      arglist += ", ";
  }
  return arglist;
}

function stackTrace(aArguments, aMaxCount) {
  dump("=[STACKTRACE]=====================================================\n");
  dump("*** at: " + stackTraceFunctionFormat(aArguments.callee.name) + "(" +
       stackTraceArgumentsFormat(aArguments) + ")\n");
  var temp = aArguments.callee.caller;
  var count = 0;
  while (temp) {
    dump("***     " + stackTraceFunctionFormat(temp.name) + "(" +
         stackTraceArgumentsFormat(temp.arguments) + ")\n");

    temp = temp.arguments.callee.caller;
    if (aMaxCount > 0 && ++count == aMaxCount)
      break;
  }
  dump("==================================================================\n");
}

function dumpFile(file) {
  dump("*** file = " + file.path + ", exists = " + file.exists() + "\n");
}
#endif