~ubuntu-branches/debian/sid/partman-base/sid

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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <parted/parted.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdbool.h>
#include <ctype.h>
#include <signal.h>
#include <stdarg.h>

/**********************************************************************
   Logging
**********************************************************************/

/* This file is used as pid-file. */
char pidfile_name[] = "/var/run/parted_server.pid";

/* These are the communication fifos */
char infifo_name[] = "/var/lib/partman/infifo";
char outfifo_name[] = "/var/lib/partman/outfifo";
char stopfifo_name[] = "/var/lib/partman/stopfifo";

/* This file is used as log-file. */
char logfile_name[] = "/var/log/partman";

/* main() opens the logfile */
FILE *logfile;

/* This string is used to prepend the messages written in the log file */
char const program_name[] = "parted_server";

/* Write a message to the log-file.  Arguments are the same as in printf.
 * Note that this deliberately uses asprintf, not xasprintf; if it fails,
 * there's nothing useful we can do, and we might be about to exit anyway.
 */
/* log(const char *format, ...) */
#define log(...) \
	({ \
                char *msg_log; \
                if (asprintf(&msg_log, __VA_ARGS__) >= 0) { \
                        fprintf(logfile, "%s: %s\n", program_name, msg_log); \
                        fflush(logfile); \
                        free(msg_log); \
                } \
        })

/* Write a line to the log-file and exit. */
/* critical_error(const char *format, ...) */
#define critical_error(...) \
        ({ \
                log(__VA_ARGS__); \
                log("Line %i. CRITICAL ERROR!!!  EXITING.", __LINE__); \
                exit(1); \
        })

/* For debugging purposes */
#define traceline() log("Line: %i", __LINE__)

#define assert(x) \
        if(!(x)) \
                critical_error("Assertion failed at line %i.", __LINE__)

#define log_partitions(dev, disk) \
        (dump_info(logfile, dev, disk), fflush(logfile))

char *
xasprintf(const char *format, ...)
{
        va_list args;
        char *result;

        va_start(args, format);
        if (vasprintf(&result, format, args) < 0) {
                if (errno == ENOMEM)
                        critical_error("Cannot allocate memory.");
                return NULL;
        }

        return result;
}

enum alignment {
        ALIGNMENT_CYLINDER,
        ALIGNMENT_MINIMAL,
        ALIGNMENT_OPTIMAL
} alignment = ALIGNMENT_OPTIMAL;

/**********************************************************************
   Reading from infifo and writing to outfifo
**********************************************************************/

/* This directory contains infifo and outfifo */
char my_directory[] = "/var/lib/partman";

/* The output FIFO.  We write to it, the clients read. */
FILE *outfifo = NULL;

/* Open the output FIFO.  After this function the global variable
   outfifo can be used for writing. */
void
open_out()
{
        char *str;
        log("Opening outfifo");
        str = xasprintf("%s/outfifo", my_directory);
        outfifo = fopen(str, "w");
        if (outfifo == NULL)
                critical_error("Can't open outfifo");
        free(str);
}

/* Write to the output FIFO.  The arguments are the same as in
   printf. */
#define oprintf(...) \
        ({ \
                char *msg_oprintf; \
                fprintf(outfifo,__VA_ARGS__); \
                fflush(outfifo); \
                msg_oprintf = xasprintf(__VA_ARGS__); \
                log("OUT: %s\n", msg_oprintf); \
                free(msg_oprintf); \
        })

/* The input FIFO.  We read from it, the clients write. */
FILE *infifo = NULL;

/* Open the input FIFO.  After this function the global variable
   infifo can be used for reading */
void
open_in()
{
        char *str;
        log("Opening infifo");
        str = xasprintf("%s/infifo", my_directory);
        infifo = fopen(str, "r");
        if (infifo == NULL)
                critical_error("Can't open infifo");
        free(str);
}

/* Do fscanf from the input FIFO.  The arguments are the same as in
   the function `scanf' */
#define iscanf(...) fscanf(infifo,__VA_ARGS__)

/* Read the remainder of this line from the input FIFO, skipping leading
 * whitespace. Sets *str to NULL if there was no data left in the FIFO (as
 * opposed to merely optional leading whitespace followed by a newline,
 * indicating an empty argument following the whitespace; in that case, set
 * *str to the empty string). Caller is expected to free *str.
 */
void
iscan_line(char **str, int expect_leading_newline)
{
        int c;

        *str = NULL;

        c = fgetc(infifo);
        if (c == EOF)
                return;
        if (c == '\n' && expect_leading_newline) {
                c = fgetc(infifo);
                if (c == EOF)
                        return;
        }
        while (c != EOF && c != '\n') {
                if (isspace((unsigned char) c))
                        c = fgetc(infifo);
                else {
                        ungetc(c, infifo);
                        break;
                }
        }

        if (c == EOF || c == '\n')
                *str = calloc(1, 1);
        else
                iscanf("%a[^\n]", str);
}

void
synchronise_with_client()
{
        char *str;
        FILE *stopfifo;
        str = xasprintf("%s/stopfifo", my_directory);
        stopfifo = fopen(str, "r");
        if (stopfifo == NULL)
                critical_error("Can't open stopfifo for synchronisation");
        free(str);
        fclose(stopfifo);
}

/* This function closes infifo and outfifo.  Then in order to
   synchronise with the clients it opens and closes first outfifo and
   afterwards infifo but in oposite direction -- outfifo for reading
   and infifo for writing. */
void
close_fifos_and_synchronise()
{
        char *str;
        int c;
        log("Closing infifo and outfifo");
        fclose(infifo);
        fclose(outfifo);
        synchronise_with_client();
        str = xasprintf("%s/outfifo", my_directory);
        outfifo = fopen(str, "r");
        if (outfifo == NULL)
                critical_error("Can't open outfifo for synchronisation");
        free(str);
        while (EOF != (c = fgetc(outfifo))) {
        }
        fclose(outfifo);
        synchronise_with_client();
        str = xasprintf("%s/infifo", my_directory);
        infifo = fopen(str, "w");
        if (infifo == NULL)
                critical_error("Can't open infifo for synchronisation");
        free(str);
        fclose(infifo);
        synchronise_with_client();
}

/**********************************************************************
   Timer
**********************************************************************/

bool timer_started = false;

/* Tell the client to open a progress bar. */
void
start_timer()
{
        assert(!timer_started);
        oprintf("Timer\n");
        timer_started = true;
}

/* Tell the client to close the progress bar. */
void
stop_timer()
{
        assert(timer_started);
        oprintf("ready\n");
        timer_started = false;
}

/* Tell the client the fraction of operation done (in permiles). */
void
timer_handler(PedTimer *timer, void *context)
{
        assert(timer_started);
        oprintf("%.0f %s\n", 1000 * timer->frac, timer->state_name);
}

/* Like ped_file_system_resize but automaticaly creates PedTimer */
int
timered_file_system_resize(PedFileSystem *fs, PedGeometry *geom)
{
        int result;
        PedTimer *timer;
        start_timer();
        timer = ped_timer_new(&timer_handler, NULL);
        result = ped_file_system_resize(fs, geom, timer);
        stop_timer();
        ped_timer_destroy(timer);
        return result;
}

/**********************************************************************
   Exception handler
**********************************************************************/

/* Generate for the client an exception using the following scenario: */
/*    1. Print `type' in outfifo */
/*    2. Print `message' to be presented to the user. */
/*    3. Print newline to mark the end of the message. */
/*    4. Print the options for the user, one per line and end with an
 *       empty line. */
/*    5. Read from infifo the user response.  This is either
 *       "unhandled" or one of the options from 4. */
/* Arguments: `type' is a string such as "information", "warning",
 * "error", etc., `message' is the text to be presented to the user
 * and `options' is an array of pointers to strings such "Yes", "No",
 * "Cancel", etc.; the last pointer is NULL.  The function returns the
 * index of the option chosen by the user or -1 if the option read in
 * 5. was "unhandled".  The client responses with "unhandled" when the
 * user cancels the debconf dialog or when the dialog was not
 * presented to the user because of the debconf priority. */
int
pseudo_exception(char *type, char *message, char **options)
{
        int i;
        char *str;
        bool timer_was_started = timer_started;
        if (timer_was_started)
                stop_timer();
        oprintf("%s\n", type);
        oprintf("%s\n", message);
        oprintf("\n");
        for (i = 0; options[i] != NULL; i++) {
                oprintf("%s\n", options[i]);
        }
        oprintf("\n");
        if (timer_was_started)
                start_timer();
        iscan_line(&str, 1);
        if (!str)
                critical_error("No data in infifo.");
        if (!strcmp(str, "unhandled")) {
                log("User canceled exception handler");
                return -1;
        }
        for (i = 0; options[i] != NULL; i++)
                if (!strcasecmp(str, options[i])) {
                        free(str);
                        return i;
                }
        critical_error("exception_handler: Bad option: \"%s\"", str);
}

/* The maximal meaningful bit in PedExceptionOption.  In the current
   version of libparted (1.6) this is 7, but let us be safer. */
#define MAXIMAL_OPTION 10
#define POWER_MAXIMAL_OPTION 1024       /* 2 to the MAXIMAL_OPTION */

/* The exception handler for ped_exception_set_handler(). */
PedExceptionOption
exception_handler(PedException *ex)
{
        char *options[MAXIMAL_OPTION + 1];
        int i;
        unsigned bit;
        int response;
        i = 0;
        for (bit = 1; bit <= POWER_MAXIMAL_OPTION; bit = bit << 1) {
                if (bit & ex->options) {
                        options[i] = ped_exception_get_option_string(bit);
                        i++;
                }
        }
        options[i] = NULL;
        response =
            pseudo_exception(ped_exception_get_type_string(ex->type),
                             ex->message, options);
        if (response == -1) {
                log("User canceled exception handler");
                return PED_EXCEPTION_UNHANDLED;
        }
        for (bit = 1; bit <= POWER_MAXIMAL_OPTION; bit = bit << 1) {
                if (bit & ex->options) {
                        char *option;
                        option = ped_exception_get_option_string(bit);
                        if (!strcasecmp(options[response], option)) {
                                return bit;
                        }
                }
        }
        critical_error("exception_handler: Bad option: <%s>",
                       options[response]);
}

/* If we want to temporarily disable the exception handler for some
   commands, we use deactivate_exception_handler() before them and
   activate_exception_handler after them. */

unsigned handler_deactivation_counter = 0;

void
deactivate_exception_handler()
{
        if (handler_deactivation_counter == 0)
                ped_exception_fetch_all();
        handler_deactivation_counter++;
}

void
activate_exception_handler()
{
        assert(handler_deactivation_counter > 0);
        handler_deactivation_counter--;
        if (handler_deactivation_counter == 0)
                ped_exception_leave_all();
}

/**********************************************************************
   Registry of the opened devices
**********************************************************************/

struct devdisk {
        char *name;
        PedDevice *dev;
        PedDisk *disk;
        bool changed;
        PedGeometry *geometries;
        int number_geometries;
        enum alignment alignment;
};

/* We store the accessed devices from `devices[0]' to
   `devices[number_devices - 1]'.  `number_devices' is a small number
   so there is no need to use a hash table or some more advanced data
   structure.  Moreover a version of parted_server using the hash
   implementation from libdebian-installer was 200 bytes longer. */

unsigned number_devices = 0;
struct devdisk *devices = NULL;

/* The size of the array `devices' */
unsigned allocated_devices = 0;

/* index = index_of_name(name);
 * 0 == strcmp(devices[index].name, name)
 *
 * Be careful not to write code like devices[index_of_name(name)].
 * This function may change devices, so a sequence point is required.
 */
int
index_of_name(const char *name)
{
        int i;
        assert(name != NULL);
        for (i = 0; i < number_devices; i++)
                if (0 == strcmp(name, devices[i].name))
                        return i;
        if (number_devices == allocated_devices) {
                allocated_devices = 1 + 2 * allocated_devices;
                devices = realloc(devices,
                                  sizeof(struct devdisk[allocated_devices]));
                if (devices == NULL)
                        critical_error("Cannot allocate memory.");
        }
        number_devices++;
        devices[i].name = strdup(name);
        if (NULL == devices[i].name)
                critical_error("Cannot allocate memory.");
        devices[i].dev = NULL;
        devices[i].disk = NULL;
        devices[i].changed = false;
        devices[i].geometries = NULL;
        devices[i].number_geometries = 0;
        devices[i].alignment = alignment;
        return i;
}

int
index_of_device(const PedDevice *dev)
{
        int i;
        assert(dev != NULL);
        for (i = 0; i < number_devices; i++)
                if (dev == devices[i].dev)
                        return i;
        return -1;
}

/* Mangle fstype to abstract changes in parted code */
void
mangle_fstype_name(char **fstype)
{
        if (!strcasecmp(*fstype, "linux-swap")) {
                free(*fstype);
                *fstype = strdup("linux-swap(v1)");
        }
}

/* Return the PedDevice of `name'. */
PedDevice *
device_named(const char *name)
{
        int index = index_of_name(name);
        return devices[index].dev;
}


/* Return the PedDisk of `name'. */
PedDisk *
disk_named(const char *name)
{
        int index = index_of_name(name);
        return devices[index].disk;
}

/* True iff the PedDevice of `name' is not NULL. */
bool
device_opened(const char *name)
{
        return NULL != device_named(name);
}

/* Set the PedDevice of `name' to be `dev'.  The old PedDevice of
   `name' (if any) will be ped_device_destroy-ed. */
void
set_device_named(const char *name, PedDevice *dev)
{
        PedDevice *old_dev;
        int index = index_of_name(name);
        assert(disk_named(name) == NULL);
        old_dev = device_named(name);
        if (NULL != old_dev)
                ped_device_destroy(old_dev);
        devices[index].dev = dev;
}

void
remember_geometries_named(const char *name)
{
        static unsigned const max_partition = 50;
        PedGeometry *geometries;
        PedDisk *disk;
        int last;
        PedPartition *part;
        int index = index_of_name(name);
        geometries = devices[index].geometries;
        if (NULL != geometries)
                free(geometries);
        disk = disk_named(name);
        if (disk == NULL) {
                devices[index].geometries = NULL;
                devices[index].number_geometries = 0;
        } else {
                geometries = malloc(sizeof(PedGeometry[max_partition]));
                last = 0;
                for (part = NULL;
                     NULL != (part = ped_disk_next_partition(disk, part));) {
                        if (PED_PARTITION_EXTENDED & part->type)
                                continue;
                        if (PED_PARTITION_METADATA & part->type)
                                continue;
                        if (PED_PARTITION_FREESPACE & part->type)
                                continue;
                        ped_geometry_init(geometries + last,
                                          disk->dev,
                                          part->geom.start, part->geom.length);
                        last = last + 1;
                        if (last >= max_partition)
                                critical_error("Too many partitions");
                }
                geometries = realloc(geometries, sizeof(PedGeometry[last]));
                if (last != 0 && geometries == NULL)
                        critical_error("Cannot allocate memory");
                devices[index].geometries = geometries;
                devices[index].number_geometries = last;
        }
}

/* Set the PedDisk of `name' to be `disk'.  The old PedDisk of `name'
   (if any) will be ped_disk_destroy-ed. */
void
set_disk_named(const char *name, PedDisk *disk)
{
        PedDisk *old_disk;
        int index = index_of_name(name);
        assert(device_opened(name));
        old_disk = disk_named(name);
        if (NULL != old_disk)
                ped_disk_destroy(old_disk);
        devices[index].disk = disk;
        if (disk) {
                if (ped_disk_is_flag_available(disk,
                                               PED_DISK_CYLINDER_ALIGNMENT))
                        ped_disk_set_flag(disk, PED_DISK_CYLINDER_ALIGNMENT,
                                          devices[index].alignment ==
                                                ALIGNMENT_CYLINDER);
                else if (0 != strcmp(disk->type->name, "gpt"))
                        /* If the PED_DISK_CYLINDER_ALIGNMENT flag isn't
                           available, then there are two alternatives:
                           either the disk label format is too old to know
                           about modern alignment (#579948), or it's too new
                           to care about cylinder alignment (#674894).  The
                           only format currently known to fall into the
                           latter category is GPT; for the others, we should
                           assume that *only* cylinder alignment is
                           available. */
                        devices[index].alignment = ALIGNMENT_CYLINDER;
        }
}

/* True if the partition doesn't exist on the storage device */
bool
named_partition_is_virtual(const char *name, PedSector start, PedSector end)
{
        PedGeometry *geometries;
        int i;
        int last;
        int index = index_of_name(name);
        log("named_partition_is_virtual(%s,%lli,%lli)", name, start, end);
        geometries = devices[index].geometries;
        last = devices[index].number_geometries;
        if (NULL == geometries) {
                log("yes");
                return true;
        }
        for (i = 0; i < last; i++) {
                if (start == geometries[i].start && end == geometries[i].end) {
                        log("no");
                        return false;
                }
        }
        log("yes");
        return true;
}

/* True iff the partition table of `name' has been changed. */
bool
named_is_changed(const char *name)
{
        int index = index_of_name(name);
        return devices[index].changed;
}

/* Note the partition table of `name' as having been changed. */
void
change_named(const char *name)
{
        int index = index_of_name(name);
        log("Note %s as changed", name);
        devices[index].changed = true;
}

/* Note the partition table of `name' as unchanged. */
void
unchange_named(const char *name)
{
        int index = index_of_name(name);
        log("Note %s as unchanged", name);
        devices[index].changed = false;
        remember_geometries_named(name);
}

/* Return the desired alignment for dev. */
enum alignment
alignment_of_device(const PedDevice *dev)
{
        int index = index_of_device(dev);
        if (index >= 0)
                return devices[index].alignment;
        else
                return ALIGNMENT_CYLINDER;
}


/**********************************************************************
   Partition creation
**********************************************************************/

/* True if `disk' has already an extended partition. */
bool
has_extended_partition(PedDisk *disk)
{
        assert(disk != NULL);
        return ped_disk_extended_partition(disk) != NULL;
}

void
set_alignment(void)
{
        const char *align_env = getenv("PARTMAN_ALIGNMENT");

        if (align_env && !strcmp(align_env, "cylinder"))
                alignment = ALIGNMENT_CYLINDER;
        else if (align_env && !strcmp(align_env, "minimal"))
                alignment = ALIGNMENT_MINIMAL;
        else
                alignment = ALIGNMENT_OPTIMAL;
}

/* Get a constraint suitable for partition creation on this disk. */
PedConstraint *
partition_creation_constraint(const PedDevice *cdev)
{
        PedSector md_grain_size;
        PedConstraint *aligned, *gap_at_end, *combined;
        PedGeometry gap_at_end_geom;
        enum alignment cdev_alignment = alignment_of_device(cdev);

        if (cdev_alignment == ALIGNMENT_OPTIMAL)
                aligned = ped_device_get_optimal_aligned_constraint(cdev);
        else if (cdev_alignment == ALIGNMENT_MINIMAL)
                aligned = ped_device_get_minimal_aligned_constraint(cdev);
        else
                aligned = ped_device_get_constraint(cdev);
        if (cdev->type == PED_DEVICE_DM)
                return aligned;

        /* We must ensure that there's a small gap at the end, since
         * otherwise MD 0.90 metadata at the end of a partition may confuse
         * mdadm into believing that both the disk and the partition
         * represent the same RAID physical volume.  0.90 metadata is
         * located by rounding the device size down to a 64K boundary and
         * subtracting 64K (1.x metadata is either between 8K and 12K from
         * the end, or at or near the start), so we round down to 64K and
         * subtract one more sector.
         */
        md_grain_size = 65536 / cdev->sector_size;
        if (md_grain_size == 0)
                md_grain_size = 1;
        ped_geometry_init(&gap_at_end_geom, cdev, 0,
                          ped_round_down_to(cdev->length, md_grain_size) - 1);
        gap_at_end = ped_constraint_new(ped_alignment_any, ped_alignment_any,
                                        &gap_at_end_geom, &gap_at_end_geom,
                                        1, cdev->length);

        combined = ped_constraint_intersect(aligned, gap_at_end);

        ped_constraint_destroy(gap_at_end);
        ped_constraint_destroy(aligned);
        return combined;
}

/* Add to `disk' a new extended partition starting at `start' and
   ending at `end' */
PedPartition *
add_extended_partition(PedDisk *disk, PedSector start, PedSector end)
{
        PedPartition *extended;
        assert(disk != NULL);
        assert(!has_extended_partition(disk));
        /* ext2 has no sense, but parted requires some argument */
        extended = ped_partition_new(disk, PED_PARTITION_EXTENDED,
                                     ped_file_system_type_get("ext2"),
                                     start, end);
        if (!extended) {
                return NULL;
        }
        if (!ped_disk_add_partition(disk, extended,
                                    ped_constraint_any(disk->dev))) {
                ped_partition_destroy(extended);
                return NULL;
        }
        return extended;
}

/* Makes the extended partition as large as possible. */
void
maximize_extended_partition(PedDisk *disk)
{
        PedPartition *extended;
        assert(disk != NULL);
        assert(has_extended_partition(disk));
        extended = ped_disk_extended_partition(disk);
        ped_disk_maximize_partition(disk, extended,
                                    ped_constraint_any(disk->dev));
}

/* Makes the extended partition as small as possible or removes it if
   there are no logical partitions. */
void
minimize_extended_partition(PedDisk *disk)
{
        assert(disk != NULL);
        if (0 != strcmp(disk->type->name, "dvh"))
                ped_disk_minimize_extended_partition(disk);
}

/* Add to `disk' a new primary partition with file system `fs_type'
   starting at `start' and ending at `end'.  Note: The partition is
   not formatted, but only created. */
PedPartition *
add_primary_partition(PedDisk *disk, PedFileSystemType *fs_type,
                      PedSector start, PedSector end)
{
        PedPartition *part;
        assert(disk != NULL);
        log("add_primary_partition(disk(%lli),%lli-%lli)",
            disk->dev->length, start, end);
        if (has_extended_partition(disk)) {
                /* Minimise the extended partition.  If there is an
                   extended partition, but no logical partitions, this
                   command removes the extended partition. */
                log("Minimizing extended partition.");
                minimize_extended_partition(disk);
        }
        part = ped_partition_new(disk, 0, fs_type, start, end);
        if (part == NULL) {
                log("Cannot create new primary partition.");
                return NULL;
        }
        if (!ped_disk_add_partition(disk, part, partition_creation_constraint(disk->dev))) {
                log("Cannot add the primary partition to partition table.");
                ped_partition_destroy(part);
                return NULL;
        }
        return part;
}

/* Add to `disk' a new logical partition with file system `fs_type'
   starting at `start' and ending at `end'.  Note: The partition is
   not formatted, but only created. */
PedPartition *
add_logical_partition(PedDisk *disk, PedFileSystemType *fs_type,
                      PedSector start, PedSector end)
{
        PedPartition *part;
        assert(disk != NULL && fs_type != NULL);
        if (!has_extended_partition(disk))
                if (!add_extended_partition(disk, start, end))
                        return NULL;
        maximize_extended_partition(disk);
        part = ped_partition_new(disk, PED_PARTITION_LOGICAL, fs_type,
                                 start, end);
        if (part == NULL) {
                minimize_extended_partition(disk);
                return NULL;
        }
        if (!ped_disk_add_partition(disk, part, partition_creation_constraint(disk->dev))) {
                ped_partition_destroy(part);
                minimize_extended_partition(disk);
                return NULL;
        }
        minimize_extended_partition(disk);
        return part;
}

/* Resizes `part' from `disk' to start from `start' and end at `end'.
   If `open_filesystem' is true and `disk' contains some file system
   then it is also resized.  Returns true on success. */
bool
resize_partition(PedDisk *disk, PedPartition *part,
                 PedSector start, PedSector end, bool open_filesystem)
{
        PedFileSystem *fs;
        PedConstraint *constraint;
        PedSector old_start, old_end;
        bool result;
        log("resize_partition(openfs=%s)", open_filesystem ? "true" : "false");
        old_start = (part->geom).start;
        old_end = (part->geom).end;
        if (old_start == start && old_end == end)
                return true;
        if (open_filesystem) {
                deactivate_exception_handler();
                fs = ped_file_system_open(&(part->geom));
                activate_exception_handler();
                log("opened file system: %s", NULL != fs ? "yes" : "no");
                if (NULL != fs && (fs->geom->start < (part->geom).start
                                   || fs->geom->end > (part->geom).end)) {
                        ped_file_system_close(fs);
                        fs = NULL;
                }
                if (NULL == fs && NULL != ped_file_system_probe(&(part->geom)))
                        return false;
                if (NULL != fs)
                        constraint = ped_file_system_get_resize_constraint(fs);
                else
                        constraint = ped_constraint_any(disk->dev);
        } else {
                PedFileSystemType *fs_type;
                PedGeometry *fs_geom;
                PedAlignment start_align;
                PedGeometry full_dev;
                fs = NULL;
                fs_type = ped_file_system_probe(&(part->geom));
                log("probed file system: %s", NULL != fs_type ? "yes" : "no");
                if (NULL != fs_type)
                        fs_geom = ped_file_system_probe_specific(fs_type,
                                                                 &part->geom);
                else
                        fs_geom = NULL;
                if (NULL != fs_geom && (fs_geom->start < (part->geom).start
                                        || fs_geom->end > (part->geom).end)) {
                        log("broken filesystem detected");
                        ped_geometry_destroy(fs_geom);
                        fs_geom = NULL;
                }
                if (NULL == fs_geom && NULL != fs_type)
                        return false;
                if (NULL != fs_geom) {
                        /* We cannot resize or move the fs but we can
                         * move the end of the partition so long as it
                         * contains the whole fs.
                         */
                        if (ped_alignment_init(&start_align, fs_geom->start, 0)
                            && ped_geometry_init(&full_dev, disk->dev,
                                                 0, disk->dev->length - 1)) {
                                constraint = ped_constraint_new(
                                        &start_align,
                                        ped_alignment_any,
                                        &full_dev, &full_dev,
                                        fs_geom->length,
                                        disk->dev->length);
                        } else {
                                constraint = NULL;
                        }
                        ped_geometry_destroy(fs_geom);
                } else {
                        constraint = ped_constraint_any(disk->dev);
                }
        }
        if (NULL == constraint) {
                log("failed to get resize constraint");
                if (NULL != fs)
                        ped_file_system_close(fs);
                return false;
        }
        if (part->type & PED_PARTITION_LOGICAL)
                maximize_extended_partition(disk);
        if (!ped_disk_set_partition_geom(disk, part, constraint, start, end))
                result = false;
        else if (NULL == fs)
                result = true;
        else if (timered_file_system_resize(fs, &(part->geom))) {
                result = true;
        } else {
                ped_disk_set_partition_geom(disk, part,
                                            ped_constraint_any(disk->dev),
                                            old_start, old_end);
                result = false;
        }
        if (fs != NULL)
                ped_file_system_close(fs);
        if (part->type & PED_PARTITION_LOGICAL)
                minimize_extended_partition(disk);
        return result;
        /* TODO: not sure if constraints here should be
           ped_constraint_destroy-ed.  Let's be safe. */
}

/**********************************************************************
   Getting info
**********************************************************************/

/* true when it is possible to create a primary partition in `space'.
   `space' must be a free space in `disk'. */
bool
possible_primary_partition(PedDisk *disk, PedPartition *space)
{
        bool result;
        assert(disk != NULL);
        assert(space != NULL && PED_PARTITION_FREESPACE & space->type);
        deactivate_exception_handler();
        result = (!(PED_PARTITION_LOGICAL & space->type)
                  && (ped_disk_get_primary_partition_count(disk)
                      < ped_disk_get_max_primary_partition_count(disk)));
        activate_exception_handler();
        return result;
}

/* true when it is possible to create an extended partition in `space'.
   `space' must be a free space in `disk'. */
bool
possible_extended_partition(PedDisk *disk, PedPartition *space)
{
        bool result;
        assert(disk != NULL);
        assert(space != NULL && PED_PARTITION_FREESPACE & space->type);
        deactivate_exception_handler();
        result = (ped_disk_type_check_feature(disk->type,
                                              PED_DISK_TYPE_EXTENDED)
                  && !has_extended_partition(disk)
                  && possible_primary_partition(disk, space));
        activate_exception_handler();
        return result;
}

/* true if the last sector of `part1' is phisicaly before the first
   sector of `part2'. */
inline bool
partition_before(PedPartition *part1, PedPartition *part2)
{
        return (part1->geom).end < (part2->geom).start;
}

/* true when it is possible to create a logical partition in `space'.
   `space' must be a free space in `disk'. */
bool
possible_logical_partition(PedDisk *disk, PedPartition *space)
{
        PedPartition *extended, *part;
        bool result;
        assert(disk != NULL);
        assert(space != NULL && (PED_PARTITION_FREESPACE & space->type));
        deactivate_exception_handler();
        if (!has_extended_partition(disk))
                result = possible_extended_partition(disk, space);
        else {
                extended = ped_disk_extended_partition(disk);
                result = true;
                part = ped_disk_next_partition(disk, NULL);
                while (result && NULL != part) {
                        if (ped_partition_is_active(part)
                            && ((partition_before(space, part)
                                 && partition_before(part, extended))
                                || (partition_before(extended, part)
                                    && partition_before(part, space)))) {
                                /* There is a primary partition between us
                                   and the extended partition. */
                                assert(!(PED_PARTITION_LOGICAL & part->type));
                                result = false;
                        }
                        part = ped_disk_next_partition(disk, part);
                }
        }
        activate_exception_handler();
        return result;
}

/* Finds in `disk' a partition with id `id' and returns it. */
PedPartition *
partition_with_id(PedDisk *disk, char *id)
{
        PedPartition *part;
        long long start, end;
        long long start_sector, end_sector;
        assert(id != NULL);
        log("partition_with_id(%s)", id);
        if (2 != sscanf(id, "%lli-%lli", &start, &end))
                critical_error("Bad id %s", id);
        start_sector = start / disk->dev->sector_size;
        end_sector = (end - disk->dev->sector_size + 1) / disk->dev->sector_size;
        if (disk == NULL)
                return NULL;
        for (part = NULL;
             NULL != (part = ped_disk_next_partition(disk, part));)
                if ((part->geom).start == start_sector
                    && (part->geom).end == end_sector)
                        return part;
        return NULL;
}

/* Returns informational string about `part' from `disk'.  Format:*/
/* Number<TAB>id<TAB>length<TAB>type<TAB>fs<TAB>path<TAB>name */
char *
partition_info(PedDisk *disk, PedPartition *part)
{
        char const *type;
        char const *fs;
        char *path;
        char const *name;
        char *result;
        assert(disk != NULL && part != NULL);
        if (PED_PARTITION_FREESPACE & part->type) {
                bool possible_primary = possible_primary_partition(disk, part);
                bool possible_logical = possible_logical_partition(disk, part);
                if (possible_primary)
                        if (possible_logical)
                                type = "pri/log";
                        else
                                type = "primary";
                else if (possible_logical)
                        type = "logical";
                else
                        type = "unusable";
        } else if (PED_PARTITION_LOGICAL & part->type)
                type = "logical";
        else
                type = "primary";

        if (PED_PARTITION_FREESPACE & part->type)
                fs = "free";
        else if (PED_PARTITION_METADATA & part->type)
                fs = "label";
        else if (PED_PARTITION_EXTENDED & part->type)
                fs = "extended";
        else if (NULL == (part->fs_type))
                fs = "unknown";
        else if (0 == strncmp(part->fs_type->name, "linux-swap", 10))
                fs = "linux-swap";
        else
                fs = part->fs_type->name;

        if (0 == strcmp(disk->type->name, "loop")) {
                path = strdup(disk->dev->path);
/*         } else if (0 == strcmp(disk->type->name, "dvh")) { */
/*                 PedPartition *p; */
/*                 int count = 1; */
/*                 int number_offset; */
/*                 for (p = NULL; */
/*                      NULL != (p = ped_disk_next_partition(disk, p));) { */
/*                         if (PED_PARTITION_METADATA & p->type) */
/*                                 continue; */
/*                         if (PED_PARTITION_FREESPACE & p->type) */
/*                                 continue; */
/*                         if (PED_PARTITION_LOGICAL & p->type) */
/*                                 continue; */
/*                         if (part->num > p->num) */
/*                                 count++; */
/*                 } */
/*                 path = ped_partition_get_path(part); */
/*                 number_offset = strlen(path); */
/*                 while (number_offset > 0 && isdigit(path[number_offset-1])) */
/*                         number_offset--; */
/*                 sprintf(path + number_offset, "%i", count); */
        } else {
                path = ped_partition_get_path(part);
        }
        if (ped_disk_type_check_feature(part->disk->type,
                                        PED_DISK_TYPE_PARTITION_NAME)
            && ped_partition_is_active(part))
                name = ped_partition_get_name(part);
        else
                name = "";
        result = xasprintf("%i\t%lli-%lli\t%lli\t%s\t%s\t%s\t%s",
                           part->num,
                           (part->geom).start * disk->dev->sector_size,
                           (part->geom).end * disk->dev->sector_size + disk->dev->sector_size - 1,
                           (part->geom).length * disk->dev->sector_size, type, fs, path, name);
        free(path);
        return result;
}

/* Print in `dumpfile' information about the `dev', `disk' and the
   partitions in `disk'. */
void
dump_info(FILE *dumpfile, PedDevice *dev, PedDisk *disk)
{
        PedPartition *part;
        deactivate_exception_handler();
        if (dev == NULL) {
                fprintf(dumpfile, "Device: no");
                activate_exception_handler();
                return;
        }
        fprintf(dumpfile, "Device: yes\n");
        fprintf(dumpfile, "Model: %s\n", dev->model);
        fprintf(dumpfile, "Path: %s\n", dev->path);
        fprintf(dumpfile, "Sector size: %lli\n", dev->sector_size);
        fprintf(dumpfile, "Sectors: %lli\n", dev->length);
        fprintf(dumpfile, "Sectors/track: %i\n", dev->bios_geom.sectors);
        fprintf(dumpfile, "Heads: %i\n", dev->bios_geom.heads);
        fprintf(dumpfile, "Cylinders: %i\n", dev->bios_geom.cylinders);
        if (disk == NULL) {
                fprintf(dumpfile, "Partition table: no\n");
                activate_exception_handler();
                return;
        }
        fprintf(dumpfile, "Partition table: yes\n");
        fprintf(dumpfile, "Type: %s\n", disk->type->name);
        fprintf(dumpfile, "Partitions: #\tid\tlength\ttype\tfs\tpath\tname\n");
        for (part = NULL;
             NULL != (part = ped_disk_next_partition(disk, part));) {
                /* TODO: there is the same code in command_get_chs */
                long long cylinder_size, track_size;
                long long start, end;
                long long cyl_start, cyl_end;
                long long head_start, head_end;
                long long sec_start, sec_end;
                char *part_info = partition_info(disk, part);
                track_size = dev->bios_geom.sectors;
                cylinder_size = track_size * dev->bios_geom.heads;
                start = (part->geom).start;
                end = (part->geom).end;
                cyl_start = start / cylinder_size;
                cyl_end = end / cylinder_size;
                start = start % cylinder_size;
                end = end % cylinder_size;
                head_start = start / track_size;
                head_end = end / track_size;
                sec_start = start % track_size;
                sec_end = end % track_size;
                fprintf(dumpfile,
                        "(%lli,%lli,%lli)\t(%lli,%lli,%lli)\t%s\n",
                        cyl_start, head_start, sec_start, cyl_end,
                        head_end, sec_end, part_info);
                free(part_info);
        }
        fprintf(dumpfile, "Dump finished.\n");
        activate_exception_handler();
}

/**********************************************************************
   Commands
*********************************************************************/

PedDevice *dev;
PedDisk *disk;
char *device_name;

void
scan_device_name()
{
        if (device_name != NULL)
                free(device_name);
        if (1 != iscanf("%as", &device_name))
                critical_error("Expected device identifier.");
        dev = device_named(device_name);
        disk = disk_named(device_name);
}

void
command_quit()
{
        log("Quitting");
        fflush(logfile);
        exit(0);
}

void
command_open()
{
        log("command_open()");
        char *device;
        scan_device_name();
        if (1 != iscanf("%as", &device))
                critical_error("Expected device name.");
        log("Request to open %s", device_name);
        open_out();
        if (device_opened(device_name)) {
                static char *only_ok[] = { "OK", NULL };
                log("Warning: the device is already opened");
                pseudo_exception("Warning",
                                 "The device is already opened.", only_ok);
        } else {
                set_device_named(device_name, ped_device_get(device));
        }
        oprintf("OK\n");
        if (NULL != device_named(device_name)) {
                oprintf("OK\n");
                deactivate_exception_handler();
                set_disk_named(device_name,
                               ped_disk_new(device_named(device_name)));
                unchange_named(device_name);
                activate_exception_handler();
        } else
                oprintf("failed\n");
        free(device);
}

void
command_close()
{
        log("command_close()");
        scan_device_name();
        open_out();
        if (!device_opened(device_name)) {
                static char *only_cancel[] = { "Cancel", NULL };
                pseudo_exception("Error",
                                 "The device is not opened!", only_cancel);
        }
        set_disk_named(device_name, NULL);
        set_device_named(device_name, NULL);
        oprintf("OK\n");
}

void
command_opened()
{
        log("command_opened()");
        scan_device_name();
        open_out();
        oprintf("OK\n");
        if (NULL != device_named(device_name)) {
                oprintf("yes\n");
        } else {
                oprintf("no\n");
        }
}

void
command_virtual()
{
        char *id;
        PedPartition *part;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_virtual()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("is virtual partition with id %s", id);
        part = partition_with_id(disk, id);
        oprintf("OK\n");
        if (named_partition_is_virtual(device_name,
                                       part->geom.start, part->geom.end)) {
                oprintf("yes\n");
        } else {
                oprintf("no\n");
        }
        free(id);
}

void
command_disk_unchanged()
{
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_disk_unchanged(%s)", device_name);
        open_out();
        oprintf("OK\n");
        unchange_named(device_name);
}

void
command_is_changed()
{
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_is_changed(%s)", device_name);
        open_out();
        oprintf("OK\n");
        if (named_is_changed(device_name))
                oprintf("yes\n");
        else
                oprintf("no\n");
}

/* Print in /var/log/partition_dump information about the disk, the
   partition table and the partitions. */
void
command_dump()
{
        FILE *dumpfile;
        static char *only_cancel[] = { "Cancel", NULL };
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_dump()");
        open_out();
        dumpfile = fopen("/var/log/partition_dump", "a+");
        if (dumpfile == NULL) {
                pseudo_exception("Error",
                                 "Can't open /var/log/partition_dump",
                                 only_cancel);
        } else {
                dump_info(dumpfile, dev, disk);
                fclose(dumpfile);
        }
        oprintf("OK\n");
}

/* Check whether we are running on a sunxi-based, freescale-based, or
   AM33XX (beaglebone black) system. */
int
is_system_with_firmware_on_disk()
{
        int cpuinfo_handle;
        int result = 0;
        char buf[4096];
        int length;

        if ((cpuinfo_handle = open("/proc/cpuinfo", O_RDONLY)) != -1) {
                length = read(cpuinfo_handle, buf, sizeof(buf)-1);
                if (length > 0) {
                        buf[length]='\0';
                        if (strstr(buf, "Allwinner") != NULL)
                                result = 1;
                        else if (strstr(buf, "Freescale") != NULL)
                                result = 1;
                        else if (strstr(buf, "AM33XX") != NULL)
                                result = 1;
                }
                close(cpuinfo_handle);
        }
        return result;
}

void
command_commit()
{
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_commit()");

        /* The boot device on sunxi-based systems needs special handling.
         * By default partman calls ped_disk_clobber when writing the
         * partition table, but on sunxi-based systems this would overwrite
         * the firmware area, resulting in an unbootable system (see
         * bug #751704).
         */
        if (is_system_with_firmware_on_disk() && !strcmp(disk->dev->path, "/dev/mmcblk0")) {
                disk->needs_clobber = 0;
                log("Sunxi/Freescale/AM33XX detected. Disabling ped_disk_clobber" \
                    "for the boot device %s to protect the firmware " \
                    "area.", disk->dev->path);
        }

        open_out();
        if (disk != NULL && named_is_changed(device_name))
                ped_disk_commit(disk);
        unchange_named(device_name);
        oprintf("OK\n");
}

void
command_undo()
{
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_undo()");
        open_out();
        log("Rereading disk label");
        deactivate_exception_handler();
        if (dev != NULL) {
                set_disk_named(device_name, NULL);
                set_disk_named(device_name, ped_disk_new(dev));
        }
        activate_exception_handler();
        unchange_named(device_name);
        oprintf("OK\n");
}

void
command_partitions()
{
        PedPartition *part;
        PedConstraint *creation_constraint;
        PedSector grain_size;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_partitions()");
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        if (disk == NULL) {
                log("No partitions");
                /* No label, hence no partitions.  When there is a
                   label, there is at least one partition because the
                   free space counts as a partition. */
                oprintf("\n");
                activate_exception_handler();
                return;
        }
        if (has_extended_partition(disk))
                minimize_extended_partition(disk);
        creation_constraint = partition_creation_constraint(dev);
        grain_size = creation_constraint->start_align->grain_size;
        ped_constraint_destroy(creation_constraint);
        for (part = NULL;
             NULL != (part = ped_disk_next_partition(disk, part));) {
                char *part_info;
                if (PED_PARTITION_EXTENDED & part->type)
                        continue;
                if (PED_PARTITION_METADATA & part->type)
                        continue;
                /* Undoubtedly the following operator is a hack.
                   Libparted tries to align the partitions at
                   appropriate boundaries but despite this it sometimes
                   reports free spaces due to aligning and even
                   allows creation of unaligned partitions in these
                   free spaces.  I am not sure if this is a bug or a
                   feature of libparted. */
                if (PED_PARTITION_FREESPACE & part->type
                    && ped_disk_type_check_feature(disk->type,
                                                   PED_DISK_TYPE_EXTENDED)
                    && ((part->geom).length
                        < dev->bios_geom.sectors * grain_size))
                        continue;
                /* Another hack :) */
                if (0 == strcmp(disk->type->name, "dvh")
                    && PED_PARTITION_LOGICAL & part->type)
                        continue;
                part_info = partition_info(disk, part);
                oprintf("%s\n", part_info);
                free(part_info);
        }
        log("Partitions printed");
        /* An empty line after the last partition */
        oprintf("\n");
        activate_exception_handler();
}

void
command_partition_info()
{
        char *id;
        PedPartition *part;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_partition_info()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("command_partition_info: info for partition with id %s", id);
        part = partition_with_id(disk, id);
        oprintf("OK\n");
        deactivate_exception_handler();
        if (part == NULL) {
                log("command_partition_info: no such a partitions");
                oprintf("\n");
        } else {
                char *part_info;
                log("command_partition_info: partition found");
                part_info = partition_info(disk, part);
                oprintf("%s\n", part_info);
                free(part_info);
        }
        free(id);
        activate_exception_handler();
}

void
command_get_chs()
{
        char *id;
        PedPartition *part;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_get_chs()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("command_get_chs: Cyl/Head/Sec for partition with id %s", id);
        part = partition_with_id(disk, id);
        oprintf("OK\n");
        deactivate_exception_handler();
        if (part == NULL) {
                log("command_get_chs: no such a partitions");
                oprintf("\n");
        } else {
                /* TODO: there is the same code in dump_info */
                long long cylinder_size, track_size;
                long long start, end;
                long long cyl_start, cyl_end;
                long long head_start, head_end;
                long long sec_start, sec_end;
                log("command_get_chs: partition found");
                track_size = dev->bios_geom.sectors;
                cylinder_size = track_size * dev->bios_geom.heads;
                start = (part->geom).start;
                end = (part->geom).end;
                cyl_start = start / cylinder_size;
                cyl_end = end / cylinder_size;
                start = start % cylinder_size;
                end = end % cylinder_size;
                head_start = start / track_size;
                head_end = end / track_size;
                sec_start = start % track_size;
                sec_end = end % track_size;
                oprintf("%lli\t%lli\t%lli\t%lli\t%lli\t%lli\n",
                        cyl_start, head_start, sec_start,
                        cyl_end, head_end, sec_end);
        }
        free(id);
        activate_exception_handler();
}

void
command_label_types()
{
        PedDiskType *type = NULL;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_label_types()");
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        while (NULL != (type = ped_disk_type_get_next(type))) {
                oprintf("%s\n", type->name);
        }
        oprintf("\n");
        activate_exception_handler();
}

void
command_valid_flags()
{
        char *id;
        PedPartition *part;
        PedPartitionFlag flag;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_valid_flags()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        part = partition_with_id(disk, id);
        oprintf("OK\n");
        deactivate_exception_handler();
        if (part == NULL || !ped_partition_is_active(part)) {
                log("No such active partition: %s", id);
        } else {
                log("Partition found (%s)", id);
                for (flag = 0; 0 != (flag = ped_partition_flag_next(flag));)
                        if (ped_partition_is_flag_available(part, flag))
                                oprintf("%s\n",
                                        ped_partition_flag_get_name(flag));
        }
        oprintf("\n");
        free(id);
        activate_exception_handler();
}

void
command_get_flags()
{
        char *id;
        PedPartition *part;
        PedPartitionFlag flag;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_get_flags()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        part = partition_with_id(disk, id);
        if (part == NULL || !ped_partition_is_active(part))
                critical_error("No such active partition: %s", id);
        log("Partition found (%s)", id);
        oprintf("OK\n");
        deactivate_exception_handler();
        for (flag = 0; 0 != (flag = ped_partition_flag_next(flag));)
                if (ped_partition_is_flag_available(part, flag)
                    && ped_partition_get_flag(part, flag))
                        oprintf("%s\n", ped_partition_flag_get_name(flag));
        oprintf("\n");
        free(id);
        activate_exception_handler();
}

void
command_set_flags()
{
        char *id, *str;
        PedPartition *part;
        PedPartitionFlag first, last, flag;
        bool *states;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_set_flags()");
        change_named(device_name);
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        part = partition_with_id(disk, id);
        if (part == NULL || !ped_partition_is_active(part))
                critical_error("No such active partition: %s", id);
        log("Partition found (%s)", id);
        oprintf("OK\n");
        deactivate_exception_handler();
        first = ped_partition_flag_next(0);
        last = first - 1;
        for (flag = first; flag != 0; flag = ped_partition_flag_next(flag))
                last = flag;
        states = malloc(sizeof(bool[last - first + 1]));
        for (flag = first; flag <= last; flag++)
                states[flag - first] = false;
        while (1) {
                iscan_line(&str, 1);
                if (!str)
                        critical_error("No data in infifo!");
                if (!strcmp(str, "NO_MORE"))
                        break;
                log("Processing flag %s", str);
                flag = ped_partition_flag_get_by_name(str);
                if (flag >= first && flag <= last) {
                        log("The flag set true.");
                        states[flag - first] = true;
                }
                free(str);
        }
        free(str);
        for (flag = 0; 0 != (flag = ped_partition_flag_next(flag));)
                if (ped_partition_is_flag_available(part, flag))
                        ped_partition_set_flag(part, flag,
                                               states[flag - first]);
        free(states);
        activate_exception_handler();
        free(id);
}

void
command_uses_names()
{
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_uses_names()");
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        if (ped_disk_type_check_feature(disk->type,
                                        PED_DISK_TYPE_PARTITION_NAME))
                oprintf("yes\n");
        else
                oprintf("no\n");
        activate_exception_handler();
}

void
command_set_name()
{
        char *id, *name;
        PedPartition *part;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_set_name()");
        change_named(device_name);
        if (!ped_disk_type_check_feature(disk->type,
                                         PED_DISK_TYPE_PARTITION_NAME))
                critical_error("This label doesn't support partition names.");
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        part = partition_with_id(disk, id);
        if (part == NULL || !ped_partition_is_active(part))
                critical_error("No such active partition: %s", id);
        log("Partition found (%s)", id);
        iscan_line(&name, 0);
        if (!name)
                critical_error("No data in infifo!");
        log("Changing name to %s", name);
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        ped_partition_set_name(part, name);
        free(name);
        free(id);
        activate_exception_handler();
}

void
command_get_max_primary()
{
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_get_max_primary()");
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        if (disk != NULL && disk->type != NULL)
                oprintf("%d\n",
                        ped_disk_get_max_primary_partition_count(disk));
        else
                oprintf("\n");
        activate_exception_handler();
}

void
command_uses_extended()
{
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_uses_extended()");
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        if (disk != NULL && disk->type != NULL
            && ped_disk_type_check_feature(disk->type, PED_DISK_TYPE_EXTENDED)
            && 0 != strcmp(disk->type->name, "dvh"))
                oprintf("yes\n");
        else
                oprintf("no\n");
        activate_exception_handler();
}

void
command_file_system_types()
{
        PedFileSystemType *type;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_file_system_types()");
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        for (type = NULL;
             NULL != (type = ped_file_system_type_get_next(type));)
                oprintf("%s\n", type->name);
        oprintf("\n");
        activate_exception_handler();
}

void
command_get_file_system()
{
        char *id;
        PedPartition *part;
        PedFileSystemType *fstype;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_get_file_system()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("command_get_file_system: File system for partition %s", id);
        part = partition_with_id(disk, id);
        oprintf("OK\n");
        if (named_partition_is_virtual(device_name,
                                       part->geom.start, part->geom.end)) {
                oprintf("none\n");
        } else {
                deactivate_exception_handler();
                fstype = ped_file_system_probe(&(part->geom));
                if (fstype == NULL) {
                        oprintf("none\n");
                } else {
                        if (0 == strncmp(part->fs_type->name, "linux-swap", 10))
                                oprintf("linux-swap\n");
                        else
                                oprintf("%s\n", fstype->name);
                }
                free(id);
                activate_exception_handler();
        }
}

void
command_change_file_system()
{
        char *id;
        PedPartition *part;
        char *s_fstype;
        PedFileSystemType *fstype;
        PedPartitionFlag flag;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        open_out();
        if (2 != iscanf("%as %as", &id, &s_fstype))
                critical_error("Expected partition id and file system");
        log("command_change_file_system(%s,%s)", id, s_fstype);
        part = partition_with_id(disk, id);
        if (part == NULL) {
                critical_error("Partition not found: %s", id);
        }
        free(id);

        mangle_fstype_name(&s_fstype);

        fstype = ped_file_system_type_get(s_fstype);
        if (fstype == NULL) {
                log("Filesystem %s not found, let's see if it is a flag",
                    s_fstype);
                flag = ped_partition_flag_get_by_name(s_fstype);
                if (ped_partition_is_flag_available(part, flag)) {
                        if (!ped_partition_get_flag(part, flag)) {
                                change_named(device_name);
                                ped_partition_set_flag(part, flag, 1);
                        } else
                                log("Flag %s already set", s_fstype);
                } else {
                        critical_error("Bad file system or flag type: %s",
                                       s_fstype);
                }
        } else {
                if (!((PED_PARTITION_FREESPACE | PED_PARTITION_METADATA |
                       PED_PARTITION_EXTENDED) & part->type) &&
                    fstype != part->fs_type) {
                        change_named(device_name);
                        ped_partition_set_system(part, fstype);
                } else
                        log("Already using filesystem %s", s_fstype);
        }
        free(s_fstype);
        oprintf("OK\n");
}

void
command_new_label()
{
        PedDiskType *type;
        char *str, *device;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_new_label()");
        change_named(device_name);
        open_out();
        if (1 != iscanf("%as", &str))
                critical_error("Expected label type");
        type = ped_disk_type_get(str);
        if (type == NULL)
                critical_error("Bad label type: %s", str);
        log("command_new_label: requested label with type %s", str);
        device = strdup(device_named(device_name)->path);
        /* The old partition table may have contained wrong
           Cylinder/Head/Sector geometry.  So it is not probably
           enough to change the partition table (i.e. `disk'). */
        set_disk_named(device_name, NULL);
        set_device_named(device_name, NULL);
        dev = ped_device_get(device);
        free(device);
        if (NULL == dev)
                critical_error("Cannot reopen %s", device_name);
        set_device_named(device_name, dev);
        log("command_new_label: creating");
        disk = ped_disk_new_fresh(dev, type);
        if (disk == NULL) {
                static char *only_cancel[] = { "Cancel", NULL };
                pseudo_exception("Error",
                                 "Can't create new disk label.", only_cancel);
        } else
                set_disk_named(device_name, disk);
        oprintf("OK\n");
        free(str);
}

void
command_new_partition()
{
        char *s_type, *s_fs_type;
        PedPartitionType type;
        PedFileSystemType *fs_type;
        long long range_start, range_end;
        char *position;
        PedSector length;
        PedSector part_start, part_end;
        PedPartition *part;
        int n;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        assert(disk != NULL);
        log("command_new_partition()");
        change_named(device_name);
        open_out();
        n = iscanf("%as %as %lli-%lli %as %lli", &s_type, &s_fs_type,
                   &range_start, &range_end, &position, &length);
        if (n != 6)
                critical_error
                    ("Expected: part_type file_system id position length");

        if (!strcasecmp(s_type, "primary"))
                type = 0;
        else if (!strcasecmp(s_type, "logical"))
                type = PED_PARTITION_LOGICAL;
        else
                critical_error("Bad partition type: %s", s_type);
        log("requested partition with type %s", s_type);
        free(s_type);

        mangle_fstype_name(&s_fs_type);

        fs_type = ped_file_system_type_get(s_fs_type);
        if (fs_type == NULL)
                critical_error("Bad file system type: %s", s_fs_type);
        log("requested partition with file system %s", s_fs_type);
        free(s_fs_type);

        if (!strcasecmp(position, "full")) {
                part_start = range_start / dev->sector_size;
                part_end = ((range_end - dev->sector_size + 1)
                            / dev->sector_size);
        } else if (!strcasecmp(position, "beginning")) {
                part_start = range_start / dev->sector_size;
                part_end = (range_start + length) / dev->sector_size;
        } else if (!strcasecmp(position, "end")) {
                part_start = (range_end - length) / dev->sector_size;
                part_end = ((range_end - dev->sector_size + 1)
                            / dev->sector_size);
        } else
                critical_error("Bad position: %s", position);
        free(position);

        if (disk == NULL)
                critical_error("No opened device or no partition table");

        if (type == 0 /* PED_PARTITION_PRIMARY */ )
                part = add_primary_partition(disk, fs_type,
                                             part_start, part_end);
        else
                part = add_logical_partition(disk, fs_type,
                                             part_start, part_end);
        oprintf("OK\n");
        deactivate_exception_handler();
        if (part) {
                char *part_info = partition_info(disk, part);
                oprintf("%s\n", part_info);
                free(part_info);
        } else
                oprintf("\n");
        activate_exception_handler();
}

void
command_delete_partition()
{
        PedPartition *part;
        char *id;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        log("command_delete_partition()");
        change_named(device_name);
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("Deleting partition with id %s", id);
        part = partition_with_id(disk, id);
        if (part == NULL)
                log("No such partition");
        else {
                PedPartitionType type = part->type;
                log("Partition found");
                ped_disk_delete_partition(disk, part);
                if (type & PED_PARTITION_LOGICAL)
                        minimize_extended_partition(disk);
                log("Partition deleted");
        }
        oprintf("OK\n");
        free(id);
}

void
command_resize_partition()
{
        PedPartition *part;
        char *id;
        long long new_size;
        PedSector start, end;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        assert(disk != NULL);
        log("command_resize_partition()");
        change_named(device_name);
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("Resizing partition with id %s", id);
        part = partition_with_id(disk, id);
        if (part == NULL)
                critical_error("No such partition");
        if (1 != iscanf(" %lli", &new_size))
                critical_error("Expected new size");
        log("New size: %lli", new_size);
        start = (part->geom).start;
        end = start + new_size / dev->sector_size - 1;
        if (named_partition_is_virtual(device_name,
                                       part->geom.start, part->geom.end)) {
                resize_partition(disk, part, start, end, false);
        } else {
                if (resize_partition(disk, part, start, end, true)) {
                        ped_disk_commit(disk);
                        unchange_named(device_name);
                }
        }
        oprintf("OK\n");
        oprintf("%lli-%lli\n", (part->geom).start * dev->sector_size,
                (part->geom).end * dev->sector_size + dev->sector_size - 1);
        free(id);
}

void
command_virtual_resize_partition()
{
        PedPartition *part;
        char *id;
        long long new_size;
        PedSector start, end;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        assert(disk != NULL);
        log("command_virtual_resize_partition()");
        change_named(device_name);
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("Resizing partition with id %s", id);
        part = partition_with_id(disk, id);
        if (part == NULL)
                critical_error("No such partition");
        if (1 != iscanf(" %lli", &new_size))
                critical_error("Expected new size");
        log("New size: %lli", new_size);
        start = (part->geom).start;
        end = start + new_size / dev->sector_size - 1;
        /* ensure that the size is not less than the requested */
        do {
                resize_partition(disk, part, start, end, false);
                end = end + 1;
        } while ((part->geom).length * dev->sector_size < new_size);
        ped_disk_commit(disk);
        unchange_named(device_name);
        oprintf("OK\n");
        oprintf("%lli-%lli\n", (part->geom).start * dev->sector_size,
                (part->geom).end * dev->sector_size + dev->sector_size - 1);
        free(id);
}

void
command_get_resize_range()
{
        char *id;
        PedPartition *part;
        PedFileSystem *fs;
        PedConstraint *constraint;
        PedGeometry *max_geom;
        long long max_size, min_size, current_size;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        assert(disk != NULL);
        log("command_get_resize_range()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        deactivate_exception_handler();
        part = partition_with_id(disk, id);
        if (part == NULL)
                critical_error("No such partition");
        if (!named_partition_is_virtual(device_name,
                                        part->geom.start, part->geom.end)) {
                fs = ped_file_system_open(&(part->geom));
                if (NULL != fs && (fs->geom->start < (part->geom).start
                                   || fs->geom->end > (part->geom).end)) {
                        ped_file_system_close(fs);
                        fs = NULL;
                } else if (NULL == fs
                           && NULL != ped_file_system_probe(&(part->geom))) {
                        oprintf("OK\n");
                        oprintf("\n");
                        free(id);
                        activate_exception_handler();
                        return;
                }
        } else {
                fs = NULL;
        }
        if (NULL != fs) {
                constraint = ped_file_system_get_resize_constraint(fs);
                ped_file_system_close(fs);
        } else {
                constraint = ped_constraint_any(disk->dev);
        }
        ped_geometry_set_start(constraint->start_range, (part->geom).start);
        ped_geometry_set_end(constraint->start_range, (part->geom).start);
        if (part->type & PED_PARTITION_LOGICAL)
                maximize_extended_partition(disk);
        max_geom = ped_disk_get_max_partition_geometry(disk, part, constraint);
        if (part->type & PED_PARTITION_LOGICAL)
                minimize_extended_partition(disk);
        min_size = constraint->min_size * dev->sector_size;
        current_size = (part->geom).length * dev->sector_size;
        if (max_geom)
                max_size = max_geom->length * dev->sector_size;
        else
                max_size = current_size;
        oprintf("OK\n");
        oprintf("%lli %lli %lli\n", min_size, current_size, max_size);
        if (max_geom)
                ped_geometry_destroy(max_geom);
        ped_constraint_destroy(constraint);
        /* TODO: Probably there are memory leaks because of constraints. */
        activate_exception_handler();
        free(id);
}

void
command_get_virtual_resize_range()
{
        char *id;
        PedPartition *part;
        PedConstraint *constraint;
        PedGeometry *max_geom;
        long long max_size, min_size, current_size;
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        assert(disk != NULL);
        log("command_get_virtual_resize_range()");
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        deactivate_exception_handler();
        part = partition_with_id(disk, id);
        if (part == NULL)
                critical_error("No such partition");
        constraint = ped_constraint_any(disk->dev);
        ped_geometry_set_start(constraint->start_range, (part->geom).start);
        ped_geometry_set_end(constraint->start_range, (part->geom).start);
        if (part->type & PED_PARTITION_LOGICAL)
                maximize_extended_partition(disk);
        max_geom = ped_disk_get_max_partition_geometry(disk, part, constraint);
        if (part->type & PED_PARTITION_LOGICAL)
                minimize_extended_partition(disk);
        min_size = constraint->min_size * dev->sector_size;
        current_size = (part->geom).length * dev->sector_size;
        if (max_geom)
                max_size = max_geom->length * dev->sector_size;
        else
                max_size = current_size;
        oprintf("OK\n");
        oprintf("%lli %lli %lli\n", min_size, current_size, max_size);
        if (max_geom)
                ped_geometry_destroy(max_geom);
        ped_constraint_destroy(constraint);
        /* TODO: Probably there are memory leaks because of constraints. */
        activate_exception_handler();
        free(id);
}

void
command_get_label_type()
{
        log("command_get_label_type()");
        scan_device_name();
        open_out();
        oprintf("OK\n");
        deactivate_exception_handler();
        if ((disk == NULL) || (disk->type == NULL)
            || (disk->type->name == NULL)) {
                oprintf("unknown\n");
        } else {
                oprintf("%s\n", disk->type->name);
        }
        activate_exception_handler();
}

void
command_is_busy()
{
        char *id;
        PedPartition *part;
        log("command_is_busy()");
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        log("command_is_busy: busy check for id %s", id);
        part = partition_with_id(disk, id);
        oprintf("OK\n");
        if (ped_partition_is_busy(part)) {
                oprintf("yes\n");
        } else {
                oprintf("no\n");
        }
        free(id);
}

void
command_alignment_offset()
{
        char *id;
        PedPartition *part;
        PedAlignment *align;
        log("command_alignment_offset()");
        scan_device_name();
        if (dev == NULL)
                critical_error("The device %s is not opened.", device_name);
        open_out();
        if (1 != iscanf("%as", &id))
                critical_error("Expected partition id");
        part = partition_with_id(disk, id);
        oprintf("OK\n");
        if (alignment_of_device(dev) == ALIGNMENT_CYLINDER)
                /* None of this is useful when using cylinder alignment. */
                oprintf("0\n");
        else {
                align = ped_device_get_minimum_alignment(dev);

                /* align->offset represents the offset of the lowest logical
                 * block on the disk from the disk's natural alignment,
                 * modulo the physical sector size (e.g. 4096 bytes), as a
                 * number of logical sectors (e.g. 512 bytes).  For a disk
                 * with 4096-byte physical sectors deliberately misaligned
                 * to make DOS-style 63-sector offsets work well, we would
                 * thus expect align->offset to be 1, as (1 + 63) * 512 /
                 * 4096 is an integer.
                 *
                 * To get the alignment offset of a *partition*, we thus
                 * need to start with align->offset (in bytes) plus the
                 * partition start position.
                 */
                oprintf("%lld\n",
                        ((align->offset + part->geom.start) *
                         dev->sector_size) %
                        dev->phys_sector_size);

                ped_alignment_destroy(align);
        }
        free(id);
}

void
make_fifo(char* name)
{
    int status;
    status = mkfifo(name, 0644);
    if ((status != 0))
            if (errno != EEXIST) {
                    perror("Cannot create FIFO");
                    exit(252);
            }
}

void
make_fifos()
{
    make_fifo(infifo_name);
    make_fifo(outfifo_name);
    make_fifo(stopfifo_name);
} 

int
write_pid_file()
{
        FILE *fd;
        int status;
        pid_t oldpid;
        if ((fd = fopen(pidfile_name, "a+")) == NULL)
                return -1;

        status = fscanf(fd, "%d", &oldpid);
        if (status != 0 && status != EOF) {
		// If kill(oldpid, 0) == 0 the process is still alive
		// so we abort
		if (kill(oldpid, 0) == 0) {
			fprintf(stderr, "Not starting: process %d still exists\n", oldpid);
			fclose(fd);
			exit(250);
		}
	}

	// Truncate the pid file and continue
	freopen(pidfile_name, "w", fd);
      
        fprintf(fd, "%d", (int)(getpid()));
        fclose(fd);
        return 0;
}

void
cleanup_and_die()
{
        if (unlink(pidfile_name) != 0)
                perror("Cannot unlink pid file");
        if (unlink(infifo_name) != 0)
                perror("Cannot unlink input FIFO");
        if (unlink(outfifo_name) != 0)
                perror("Cannot unlink output FIFO");
        if (unlink(stopfifo_name) != 0)
                perror("Cannot unlink stop FIFO");
}

void
prnt_sig_hdlr(int signal)
{
        int status;
        switch(signal) {
                // SIGUSR1 signals that child is ready to take
                // requests (i.e. has finished initialisation)
                case SIGUSR1:
                    exit(0);
                    break;
                // We'll only get SIGCHLD if our child has pre-deceased us
                // In this case we should exit with its error code
                case SIGCHLD:
                    if (waitpid(-1, &status, WNOHANG) < 0)
                        exit(0);
                    if (WIFEXITED(status))
                        exit(WEXITSTATUS(status));
                    break;
                default:
                    break;
        }
}

/**********************************************************************
   Main
**********************************************************************/

void main_loop() __attribute__ ((noreturn));

void
main_loop()
{
        char *str;
        int iteration = 1;
        set_alignment();
        while (1) {
                log("main_loop: iteration %i", iteration++);
                open_in();
                if (1 != iscanf("%as", &str))
                        critical_error("No data in infifo.");
                log("Read command: %s", str);
                /* Keep partman-command in sync with changes here. */
                if (!strcasecmp(str, "QUIT"))
                        command_quit();
                else if (!strcasecmp(str, "OPEN"))
                        command_open();
                else if (!strcasecmp(str, "CLOSE"))
                        command_close();
                else if (!strcasecmp(str, "OPENED"))
                        command_opened();
                else if (!strcasecmp(str, "VIRTUAL"))
                        command_virtual();
                else if (!strcasecmp(str, "DISK_UNCHANGED"))
                        command_disk_unchanged();
                else if (!strcasecmp(str, "IS_CHANGED"))
                        command_is_changed();
                else if (!strcasecmp(str, "DUMP"))
                        command_dump();
                else if (!strcasecmp(str, "COMMIT"))
                        command_commit();
                else if (!strcasecmp(str, "UNDO"))
                        command_undo();
                else if (!strcasecmp(str, "PARTITIONS"))
                        command_partitions();
                else if (!strcasecmp(str, "PARTITION_INFO"))
                        command_partition_info();
                else if (!strcasecmp(str, "GET_CHS"))
                        command_get_chs();
                else if (!strcasecmp(str, "LABEL_TYPES"))
                        command_label_types();
                else if (!strcasecmp(str, "VALID_FLAGS"))
                        command_valid_flags();
                else if (!strcasecmp(str, "GET_FLAGS"))
                        command_get_flags();
                else if (!strcasecmp(str, "SET_FLAGS"))
                        command_set_flags();
                else if (!strcasecmp(str, "SET_NAME"))
                        command_set_name();
                else if (!strcasecmp(str, "USES_NAMES"))
                        command_uses_names();
                else if (!strcasecmp(str, "GET_MAX_PRIMARY"))
                        command_get_max_primary();
                else if (!strcasecmp(str, "USES_EXTENDED"))
                        command_uses_extended();
                else if (!strcasecmp(str, "FILE_SYSTEM_TYPES"))
                        command_file_system_types();
                else if (!strcasecmp(str, "GET_FILE_SYSTEM"))
                        command_get_file_system();
                else if (!strcasecmp(str, "CHANGE_FILE_SYSTEM"))
                        command_change_file_system();
                else if (!strcasecmp(str, "NEW_LABEL"))
                        command_new_label();
                else if (!strcasecmp(str, "NEW_PARTITION"))
                        command_new_partition();
                else if (!strcasecmp(str, "DELETE_PARTITION"))
                        command_delete_partition();
                else if (!strcasecmp(str, "RESIZE_PARTITION"))
                        command_resize_partition();
                else if (!strcasecmp(str, "GET_RESIZE_RANGE"))
                        command_get_resize_range();
                /* these two functions are undocumented and should disappear */
                else if (!strcasecmp(str, "VIRTUAL_RESIZE_PARTITION"))
                        command_virtual_resize_partition();
                else if (!strcasecmp(str, "GET_VIRTUAL_RESIZE_RANGE"))
                        command_get_virtual_resize_range();
                else if (!strcasecmp(str, "GET_LABEL_TYPE"))
                        command_get_label_type();
                else if (!strcasecmp(str, "IS_BUSY"))
                        command_is_busy();
                else if (!strcasecmp(str, "ALIGNMENT_OFFSET"))
                        command_alignment_offset();
                else
                        critical_error("Unknown command %s", str);
                free(str);
                close_fifos_and_synchronise();
        }
}

int
main(int argc, char *argv[])
{
        struct sigaction act, oldact;
        int i;

        /* Close all extraneous file descriptors, including our pipe to
         * debconf.
         */
        for (i = 3; i < 256; ++i)
                close(i);

        // Set up signal handling
        memset(&act,0,sizeof(struct sigaction));
        memset(&oldact,0,sizeof(struct sigaction));
        act.sa_handler = prnt_sig_hdlr;
        sigemptyset(&act.sa_mask);

        // Set up signal handling for parent
        if  ((sigaction(SIGCHLD, &act, &oldact) < 0)
          || (sigaction(SIGUSR1, &act, &oldact) < 0))
        {
            fprintf(stderr, "Could not set up signal handling for parent\n");
            exit(251);
        }
      
        // The parent process should wait; we die once child is
        // initialised (signalled by a SIGUSR1)
        if (fork()) {
            while (1) { sleep(5); };
        }

        // Set up signal handling for child
        if  ((sigaction(SIGCHLD, &oldact, NULL) < 0)
          || (sigaction(SIGUSR1, &oldact, NULL) < 0))
        {
            fprintf(stderr, "Could not set up signal handling for child\n");
            exit(250);
        }

        // Continue as a daemon process
        logfile = fopen(logfile_name, "a+");
        if (logfile == NULL) {
                fprintf(stderr, "Cannot append to the log file\n");
                exit(255);
        }
        if (write_pid_file() != 0) {
                fprintf(stderr, "Cannot open pid file\n");
                exit(254);
        }
        if (atexit(cleanup_and_die) != 0) {
                fprintf(stderr, "Cannot set atexit routine\n");
                exit(253);
        }
        make_fifos();
        // Signal that we've finished initialising so that the parent process
        // can die and the shell scripts can continue
        kill(getppid(), SIGUSR1);
        ped_exception_set_handler(exception_handler);
        log("======= Starting the server");
        main_loop();
}

/*
The following command can be used to format this file in a consistent
with codingstyle.txt way:

indent parted_server.c -kr -i8 -nut -psl -l79 -T FILE -T bool -T PedSector -T PedDeviceType -T PedDevice -T PedDiskTypeFeature -T PedDiskType -T PedDisk -T PedGeometry -T PedPartitionType -T PedPartitionFlag -T PedPartition -T PedFileSystemType -T PedFileSystem -T PedConstraint -T PedAlignment -T PedTimer -T PedExceptionType -T PedExceptionOption -T PedException
*/

/*
Local variables:
indent-tabs-mode: nil
c-file-style: "linux"
c-font-lock-extra-types: ("FILE" "\\sw+_t" "bool" "Ped\\sw+")
End:
*/