summaryrefslogtreecommitdiffstats
path: root/src/usermod.c
blob: f889698452a4841735f67e802c555787d61b52cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
/*
 * SPDX-FileCopyrightText: 1991 - 1994, Julianne Frances Haugh
 * SPDX-FileCopyrightText: 1996 - 2000, Marek Michałkiewicz
 * SPDX-FileCopyrightText: 2000 - 2006, Tomasz Kłoczko
 * SPDX-FileCopyrightText: 2007 - 2011, Nicolas François
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <config.h>

#ident "$Id$"

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <grp.h>
#ifdef ENABLE_LASTLOG
#include <lastlog.h>
#endif /* ENABLE_LASTLOG */
#include <pwd.h>
#ifdef ACCT_TOOLS_SETUID
#ifdef USE_PAM
#include "pam_defs.h"
#endif				/* USE_PAM */
#endif				/* ACCT_TOOLS_SETUID */
#include <stdio.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>

#include "alloc.h"
#include "atoi/str2i.h"
#include "chkname.h"
#include "defines.h"
#include "faillog.h"
#include "getdef.h"
#include "groupio.h"
#include "memzero.h"
#include "nscd.h"
#include "sssd.h"
#include "prototypes.h"
#include "pwauth.h"
#include "pwio.h"
#ifdef	SHADOWGRP
#include "sgroupio.h"
#endif
#include "shadowio.h"
#ifdef ENABLE_SUBIDS
#include "subordinateio.h"
#endif				/* ENABLE_SUBIDS */
#ifdef WITH_SELINUX
#include <selinux/selinux.h>
#endif				/* WITH_SELINUX */
#ifdef WITH_TCB
#include "tcbfuncs.h"
#endif
#include "shadowlog.h"
#include "string/sprintf.h"
#include "time/day_to_str.h"


/*
 * exit status values
 * for E_GRP_UPDATE and E_NOSPACE (not used yet), other update requests
 * will be implemented (as documented in the Solaris 2.x man page).
 */
/*@-exitarg@*/
#define E_SUCCESS	0	/* success */
#define E_PW_UPDATE	1	/* can't update password file */
#define E_USAGE		2	/* invalid command syntax */
#define E_BAD_ARG	3	/* invalid argument to option */
#define E_UID_IN_USE	4	/* UID already in use (and no -o) */
/* #define E_BAD_PWFILE	5	   passwd file contains errors */
#define E_NOTFOUND	6	/* specified user/group doesn't exist */
#define E_USER_BUSY	8	/* user to modify is logged in */
#define E_NAME_IN_USE	9	/* username or group name already in use */
#define E_GRP_UPDATE	10	/* can't update group file */
/* #define E_NOSPACE	11	   insufficient space to move home dir */
#define E_HOMEDIR	12	/* unable to complete home dir move */
#define E_SE_UPDATE	13	/* can't update SELinux user mapping */
#ifdef ENABLE_SUBIDS
#define E_SUB_UID_UPDATE 16	/* can't update the subordinate uid file */
#define E_SUB_GID_UPDATE 18	/* can't update the subordinate gid file */
#endif				/* ENABLE_SUBIDS */

#define	VALID(s)	(strcspn (s, ":\n") == strlen (s))

/*
 * Global variables
 */
static const char Prog[] = "usermod";

static char *user_name;
static char *user_newname;
static char *user_pass;
static uid_t user_id;
static uid_t user_newid;
static gid_t user_gid;
static gid_t user_newgid;
static char *user_comment;
static char *user_newcomment;
static char *user_home;
static char *user_newhome;
static char *user_shell;
#ifdef WITH_SELINUX
static const char *user_selinux = "";
static const char *user_selinux_range = NULL;
#endif				/* WITH_SELINUX */
static char *user_newshell;
static long user_expire;
static long user_newexpire;
static long user_inactive;
static long user_newinactive;
static long sys_ngroups;
static char **user_groups;	/* NULL-terminated list */

static const char* prefix = "";
static char* prefix_user_home = NULL;
static char* prefix_user_newhome = NULL;

static bool
    aflg = false,		/* append to existing secondary group set */
    cflg = false,		/* new comment (GECOS) field */
    dflg = false,		/* new home directory */
    eflg = false,		/* days since 1970-01-01 when account becomes expired */
    fflg = false,		/* days until account with expired password is locked */
    gflg = false,		/* new primary group ID */
    Gflg = false,		/* new secondary group set */
    Lflg = false,		/* lock the password */
    lflg = false,		/* new user name */
    mflg = false,		/* create user's home directory if it doesn't exist */
    oflg = false,		/* permit non-unique user ID to be specified with -u */
    pflg = false,		/* new encrypted password */
    rflg = false,		/* remove a user from a single group */
    sflg = false,		/* new shell program */
#ifdef WITH_SELINUX
    Zflg = false,		/* new selinux user */
#endif
#ifdef ENABLE_SUBIDS
    vflg = false,		/*    add subordinate uids */
    Vflg = false,		/* delete subordinate uids */
    wflg = false,		/*    add subordinate gids */
    Wflg = false,		/* delete subordinate gids */
#endif				/* ENABLE_SUBIDS */
    uflg = false,		/* specify new user ID */
    Uflg = false;		/* unlock the password */

static bool is_shadow_pwd;

#ifdef SHADOWGRP
static bool is_shadow_grp;
#endif

#ifdef ENABLE_SUBIDS
static bool is_sub_uid = false;
static bool is_sub_gid = false;
#endif				/* ENABLE_SUBIDS */

static bool pw_locked  = false;
static bool spw_locked = false;
static bool gr_locked  = false;
#ifdef SHADOWGRP
static bool sgr_locked = false;
#endif
#ifdef ENABLE_SUBIDS
static bool sub_uid_locked = false;
static bool sub_gid_locked = false;
#endif				/* ENABLE_SUBIDS */


/* local function prototypes */
static int get_groups (char *);
NORETURN static void usage (int status);
static void new_pwent (struct passwd *);
static void new_spent (struct spwd *);
NORETURN static void fail_exit (int);
static void update_group_file(void);
static void update_group(const struct group *grp);

#ifdef SHADOWGRP
static void update_gshadow_file(void);
static void update_gshadow(const struct sgrp *sgrp);
#endif
static void grp_update (void);

static void process_flags (int, char **);
static void close_files (void);
static void open_files (void);
static void usr_update (void);
static void move_home (void);
#ifdef ENABLE_LASTLOG
static void update_lastlog (void);
#endif /* ENABLE_LASTLOG */
static void update_faillog (void);

#ifndef NO_MOVE_MAILBOX
static void move_mailbox (void);
#endif

extern int allow_bad_names;

/*
 * get_groups - convert a list of group names to an array of group IDs
 *
 *	get_groups() takes a comma-separated list of group names and
 *	converts it to a NULL-terminated array. Any unknown group names are
 *	reported as errors.
 */
static int get_groups (char *list)
{
	char *cp;
	struct group *grp;
	int errors = 0;
	int ngroups = 0;

	/*
	 * Initialize the list to be empty
	 */
	user_groups[0] = NULL;

	if ('\0' == *list) {
		return 0;
	}

	/*
	 * So long as there is some data to be converted, strip off each
	 * name and look it up. A mix of numerical and string values for
	 * group identifiers is permitted.
	 */
	do {
		/*
		 * Strip off a single name from the list
		 */
		cp = strchr (list, ',');
		if (NULL != cp) {
			*cp = '\0';
			cp++;
		}

		/*
		 * Names starting with digits are treated as numerical GID
		 * values, otherwise the string is looked up as is.
		 */
		grp = prefix_getgr_nam_gid (list);

		/*
		 * There must be a match, either by GID value or by
		 * string name.
		 */
		if (NULL == grp) {
			fprintf (stderr, _("%s: group '%s' does not exist\n"),
			         Prog, list);
			errors++;
		}
		list = cp;

		/*
		 * If the group doesn't exist, don't dump core. Instead,
		 * try the next one.  --marekm
		 */
		if (NULL == grp) {
			continue;
		}

		if (ngroups == sys_ngroups) {
			fprintf (stderr,
			         _("%s: too many groups specified (max %d).\n"),
			         Prog, ngroups);
			gr_free (grp);
			break;
		}

		/*
		 * Add the group name to the user's list of groups.
		 */
		user_groups[ngroups++] = xstrdup (grp->gr_name);
		gr_free (grp);
	} while (NULL != list);

	user_groups[ngroups] = NULL;

	/*
	 * Any errors in finding group names are fatal
	 */
	if (0 != errors) {
		return -1;
	}

	return 0;
}

#ifdef ENABLE_SUBIDS
struct ulong_range
{
	unsigned long first;
	unsigned long last;
};

static struct ulong_range getulong_range(const char *str)
{
	struct ulong_range result = { .first = ULONG_MAX, .last = 0 };
	long long first, last;
	char *pos;

	errno = 0;
	first = strtoll(str, &pos, 10);
	if (('\0' == *str) || ('-' != *pos ) || (0 != errno) ||
	    (first != (unsigned long)first))
		goto out;

	errno = 0;
	last = strtoll(pos + 1, &pos, 10);
	if (('\0' != *pos ) || (0 != errno) ||
	    (last != (unsigned long)last))
		goto out;

	if (first > last)
		goto out;

	/*
	 * uid_t in linux is an unsigned int, anything over this is an invalid
	 * range will be later refused anyway by get_map_ranges().
	 */
	if (first > UINT_MAX || last > UINT_MAX)
		goto out;

	result.first = (unsigned long)first;
	result.last = (unsigned long)last;
out:
	return result;
}

struct ulong_range_list_entry {
	struct ulong_range_list_entry *next;
	struct ulong_range range;
};

static struct ulong_range_list_entry *add_sub_uids = NULL, *del_sub_uids = NULL;
static struct ulong_range_list_entry *add_sub_gids = NULL, *del_sub_gids = NULL;

static int prepend_range(const char *str, struct ulong_range_list_entry **head)
{
	struct ulong_range range;
	struct ulong_range_list_entry *entry;
	range = getulong_range(str);
	if (range.first > range.last)
		return 0;

	entry = MALLOC(1, struct ulong_range_list_entry);
	if (!entry) {
		fprintf (stderr,
			_("%s: failed to allocate memory: %s\n"),
			Prog, strerror (errno));
		return 0;
	}
	entry->next = *head;
	entry->range = range;
	*head = entry;
	return 1;
}
#endif				/* ENABLE_SUBIDS */

/*
 * usage - display usage message and exit
 */
NORETURN
static void
usage (int status)
{
	FILE *usageout = (E_SUCCESS != status) ? stderr : stdout;
	(void) fprintf (usageout,
	                _("Usage: %s [options] LOGIN\n"
	                  "\n"
	                  "Options:\n"),
	                Prog);
	(void) fputs (_("  -a, --append                  append the user to the supplemental GROUPS\n"
	                "                                mentioned by the -G option without removing\n"
	                "                                the user from other groups\n"), usageout);
	(void) fputs (_("  -b, --badname                 allow bad names\n"), usageout);
	(void) fputs (_("  -c, --comment COMMENT         new value of the GECOS field\n"), usageout);
	(void) fputs (_("  -d, --home HOME_DIR           new home directory for the user account\n"), usageout);
	(void) fputs (_("  -e, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE\n"), usageout);
	(void) fputs (_("  -f, --inactive INACTIVE       set password inactive after expiration\n"
	                "                                to INACTIVE\n"), usageout);
	(void) fputs (_("  -g, --gid GROUP               force use GROUP as new primary group\n"), usageout);
	(void) fputs (_("  -G, --groups GROUPS           new list of supplementary GROUPS\n"), usageout);
	(void) fputs (_("  -h, --help                    display this help message and exit\n"), usageout);
	(void) fputs (_("  -l, --login NEW_LOGIN         new value of the login name\n"), usageout);
	(void) fputs (_("  -L, --lock                    lock the user account\n"), usageout);
	(void) fputs (_("  -m, --move-home               move contents of the home directory to the\n"
	                "                                new location (use only with -d)\n"), usageout);
	(void) fputs (_("  -o, --non-unique              allow using duplicate (non-unique) UID\n"), usageout);
	(void) fputs (_("  -p, --password PASSWORD       use encrypted password for the new password\n"), usageout);
	(void) fputs (_("  -P, --prefix PREFIX_DIR       prefix directory where are located the /etc/* files\n"), usageout);
	(void) fputs (_("  -r, --remove                  remove the user from only the supplemental GROUPS\n"
	                "                                mentioned by the -G option without removing\n"
	                "                                the user from other groups\n"), usageout);
	(void) fputs (_("  -R, --root CHROOT_DIR         directory to chroot into\n"), usageout);
	(void) fputs (_("  -s, --shell SHELL             new login shell for the user account\n"), usageout);
	(void) fputs (_("  -u, --uid UID                 new UID for the user account\n"), usageout);
	(void) fputs (_("  -U, --unlock                  unlock the user account\n"), usageout);
#ifdef ENABLE_SUBIDS
	(void) fputs (_("  -v, --add-subuids FIRST-LAST  add range of subordinate uids\n"), usageout);
	(void) fputs (_("  -V, --del-subuids FIRST-LAST  remove range of subordinate uids\n"), usageout);
	(void) fputs (_("  -w, --add-subgids FIRST-LAST  add range of subordinate gids\n"), usageout);
	(void) fputs (_("  -W, --del-subgids FIRST-LAST  remove range of subordinate gids\n"), usageout);
#endif				/* ENABLE_SUBIDS */
#ifdef WITH_SELINUX
	(void) fputs (_("  -Z, --selinux-user SEUSER     new SELinux user mapping for the user account\n"), usageout);
	(void) fputs (_("      --selinux-range SERANGE   new SELinux MLS range for the user account\n"), usageout);
#endif				/* WITH_SELINUX */
	(void) fputs ("\n", usageout);
	exit (status);
}

/*
 * update encrypted password string (for both shadow and non-shadow
 * passwords)
 */
static char *new_pw_passwd (char *pw_pass)
{
	if (Lflg && ('!' != pw_pass[0])) {
		char *buf = XMALLOC(strlen(pw_pass) + 2, char);

#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "updating passwd", user_newname, user_newid, 0);
#endif
		SYSLOG ((LOG_INFO, "lock user '%s' password", user_newname));
		strcpy (buf, "!");
		strcat (buf, pw_pass);
		pw_pass = buf;
	} else if (Uflg && pw_pass[0] == '!') {
		if (pw_pass[1] == '\0') {
			fprintf (stderr,
			         _("%s: unlocking the user's password would result in a passwordless account.\n"
			           "You should set a password with usermod -p to unlock this user's password.\n"),
			         Prog);
			return pw_pass;
		}

#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "updating password", user_newname, user_newid, 0);
#endif
		SYSLOG ((LOG_INFO, "unlock user '%s' password", user_newname));
		memmove(pw_pass, pw_pass + 1, strlen(pw_pass));
	} else if (pflg) {
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing password", user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO, "change user '%s' password", user_newname));
		pw_pass = xstrdup (user_pass);
	}
	return pw_pass;
}

/*
 * new_pwent - initialize the values in a password file entry
 *
 *	new_pwent() takes all of the values that have been entered and fills
 *	in a (struct passwd) with them.
 */
static void new_pwent (struct passwd *pwent)
{
	if (lflg) {
		if (pw_locate (user_newname) != NULL) {
			/* This should never happen.
			 * It was already checked that the user doesn't
			 * exist on the system.
			 */
			fprintf (stderr,
			         _("%s: user '%s' already exists in %s\n"),
			         Prog, user_newname, pw_dbname ());
			fail_exit (E_NAME_IN_USE);
		}
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing name", user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO,
		         "change user name '%s' to '%s'",
		         pwent->pw_name, user_newname));
		pwent->pw_name = xstrdup (user_newname);
	}
	/* Update the password in passwd if there is no shadow file or if
	 * the password is currently in passwd (pw_passwd != "x").
	 * We do not force the usage of shadow passwords if they are not
	 * used for this account.
	 */
	if (   (!is_shadow_pwd)
	    || (strcmp (pwent->pw_passwd, SHADOW_PASSWD_STRING) != 0)) {
		pwent->pw_passwd = new_pw_passwd (pwent->pw_passwd);
	}

	if (uflg) {
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing uid", user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO,
		         "change user '%s' UID from '%d' to '%d'",
		         pwent->pw_name, pwent->pw_uid, user_newid));
		pwent->pw_uid = user_newid;
	}
	if (gflg) {
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing primary group",
		              user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO,
		         "change user '%s' GID from '%d' to '%d'",
		         pwent->pw_name, pwent->pw_gid, user_newgid));
		pwent->pw_gid = user_newgid;
	}
	if (cflg) {
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing comment", user_newname, user_newid, 1);
#endif
		pwent->pw_gecos = user_newcomment;
	}

	if (dflg) {
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing home directory",
		              user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO,
		         "change user '%s' home from '%s' to '%s'",
		         pwent->pw_name, pwent->pw_dir, user_newhome));

		if (strlen(user_newhome) > 1
			&& '/' == user_newhome[strlen(user_newhome)-1]) {
			user_newhome[strlen(user_newhome)-1]='\0';
		}

		pwent->pw_dir = user_newhome;
	}
	if (sflg) {
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing user shell",
		              user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO,
		         "change user '%s' shell from '%s' to '%s'",
		         pwent->pw_name, pwent->pw_shell, user_newshell));
		pwent->pw_shell = user_newshell;
	}
}

/*
 * new_spent - initialize the values in a shadow password file entry
 *
 *	new_spent() takes all of the values that have been entered and fills
 *	in a (struct spwd) with them.
 */
static void new_spent (struct spwd *spent)
{
	if (lflg) {
		if (spw_locate (user_newname) != NULL) {
			fprintf (stderr,
			         _("%s: user '%s' already exists in %s\n"),
			         Prog, user_newname, spw_dbname ());
			fail_exit (E_NAME_IN_USE);
		}
		spent->sp_namp = xstrdup (user_newname);
	}

	if (fflg) {
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing inactive days",
		              user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO,
		         "change user '%s' inactive from '%ld' to '%ld'",
		         spent->sp_namp, spent->sp_inact, user_newinactive));
		spent->sp_inact = user_newinactive;
	}
	if (eflg) {
		/* log dates rather than numbers of days. */
		char new_exp[16], old_exp[16];

		DAY_TO_STR(new_exp, user_newexpire);
		DAY_TO_STR(old_exp, user_expire);
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
		              "changing expiration date",
		              user_newname, user_newid, 1);
#endif
		SYSLOG ((LOG_INFO,
		         "change user '%s' expiration from '%s' to '%s'",
		         spent->sp_namp, old_exp, new_exp));
		spent->sp_expire = user_newexpire;
	}

	/* Always update the shadowed password if there is a shadow entry
	 * (even if shadowed passwords might not be enabled for this
	 * account (pw_passwd != "x")).
	 * It seems better to update the password in both places in case a
	 * shadow and a non shadow entry exist.
	 * This might occur if:
	 *  + there were already both entries
	 *  + aging has been requested
	 */
	spent->sp_pwdp = new_pw_passwd (spent->sp_pwdp);

	if (pflg) {
		spent->sp_lstchg = gettime () / DAY;
		if (0 == spent->sp_lstchg) {
			/* Better disable aging than requiring a password
			 * change. */
			spent->sp_lstchg = -1;
		}
	}
}

/*
 * fail_exit - exit with an error code after unlocking files
 */
NORETURN
static void
fail_exit (int code)
{
	if (gr_locked) {
		if (gr_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
			/* continue */
		}
	}
#ifdef	SHADOWGRP
	if (sgr_locked) {
		if (sgr_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
			/* continue */
		}
	}
#endif
	if (spw_locked) {
		if (spw_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
			/* continue */
		}
	}
	if (pw_locked) {
		if (pw_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
			/* continue */
		}
	}
#ifdef ENABLE_SUBIDS
	if (sub_uid_locked) {
		if (sub_uid_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sub_uid_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", sub_uid_dbname ()));
			/* continue */
		}
	}
	if (sub_gid_locked) {
		if (sub_gid_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sub_gid_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", sub_gid_dbname ()));
			/* continue */
		}
	}
#endif				/* ENABLE_SUBIDS */

#ifdef WITH_AUDIT
	audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
	              "modifying account",
	              user_name, AUDIT_NO_ID, 0);
#endif
	exit (code);
}


static void
update_group_file(void)
{
	const struct group  *grp;

	/*
	 * Scan through the entire group file looking for the groups that
	 * the user is a member of.
	 */
	while ((grp = gr_next()) != NULL)
		update_group(grp);
}


static void
update_group(const struct group *grp)
{
	bool          changed;
	bool          is_member;
	bool          was_member;
	struct group  *ngrp;

	changed = false;

	/*
	 * See if the user specified this group as one of their
	 * concurrent groups.
	 */
	was_member = is_on_list (grp->gr_mem, user_name);
	is_member = Gflg && (   (was_member && aflg)
			     || is_on_list (user_groups, grp->gr_name));

	if (!was_member && !is_member)
		return;

	/*
	* If rflg+Gflg  is passed in AKA -rG invert is_member flag, which removes
	* mentioned groups while leaving the others.
	*/
	if (Gflg && rflg) {
		is_member = !is_member;
	}

	ngrp = __gr_dup (grp);
	if (NULL == ngrp) {
		fprintf (stderr,
			 _("%s: Out of memory. Cannot update %s.\n"),
			 Prog, gr_dbname ());
		fail_exit (E_GRP_UPDATE);
	}

	if (was_member) {
		if ((!Gflg) || is_member) {
			/* User was a member and is still a member
			 * of this group.
			 * But the user might have been renamed.
			 */
			if (lflg) {
				ngrp->gr_mem = del_list (ngrp->gr_mem,
							 user_name);
				ngrp->gr_mem = add_list (ngrp->gr_mem,
							 user_newname);
				changed = true;
#ifdef WITH_AUDIT
				audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
					      "changing group member",
					      user_newname, AUDIT_NO_ID, 1);
#endif
				SYSLOG ((LOG_INFO,
					 "change '%s' to '%s' in group '%s'",
					 user_name, user_newname,
					 ngrp->gr_name));
			}
		} else {
			/* User was a member but is no more a
			 * member of this group.
			 */
			ngrp->gr_mem = del_list (ngrp->gr_mem, user_name);
			changed = true;
#ifdef WITH_AUDIT
			audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
				      "removing group member",
				      user_name, AUDIT_NO_ID, 1);
#endif
			SYSLOG ((LOG_INFO,
				 "delete '%s' from group '%s'",
				 user_name, ngrp->gr_name));
		}
	} else if (is_member) {
		/* User was not a member but is now a member this
		 * group.
		 */
		ngrp->gr_mem = add_list (ngrp->gr_mem, user_newname);
		changed = true;
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
			      "adding user to group",
			      user_name, AUDIT_NO_ID, 1);
#endif
		SYSLOG ((LOG_INFO, "add '%s' to group '%s'",
			 user_newname, ngrp->gr_name));
	}
	if (!changed)
		goto free_ngrp;

	if (gr_update (ngrp) == 0) {
		fprintf (stderr,
			 _("%s: failed to prepare the new %s entry '%s'\n"),
			 Prog, gr_dbname (), ngrp->gr_name);
		SYSLOG ((LOG_WARN, "failed to prepare the new %s entry '%s'", gr_dbname (), ngrp->gr_name));
		fail_exit (E_GRP_UPDATE);
	}

free_ngrp:
	gr_free(ngrp);
}


#ifdef SHADOWGRP
static void
update_gshadow_file(void)
{
	const struct sgrp  *sgrp;

	/*
	 * Scan through the entire shadow group file looking for the groups
	 * that the user is a member of.
	 */
	while ((sgrp = sgr_next()) != NULL)
		update_gshadow(sgrp);
}
#endif				/* SHADOWGRP */


#ifdef SHADOWGRP
static void
update_gshadow(const struct sgrp *sgrp)
{
	bool         changed;
	bool         is_member;
	bool         was_member;
	bool         was_admin;
	struct sgrp  *nsgrp;

	changed = false;

	/*
	 * See if the user was a member of this group
	 */
	was_member = is_on_list (sgrp->sg_mem, user_name);

	/*
	 * See if the user was an administrator of this group
	 */
	was_admin = is_on_list (sgrp->sg_adm, user_name);

	/*
	 * See if the user specified this group as one of their
	 * concurrent groups.
	 */
	is_member = Gflg && (   (was_member && aflg)
			     || is_on_list (user_groups, sgrp->sg_name));

	if (!was_member && !was_admin && !is_member)
		return;

	/*
	* If rflg+Gflg  is passed in AKA -rG invert is_member, to remove targeted
	* groups while leaving the user apart of groups not mentioned
	*/
	if (Gflg && rflg) {
		is_member = !is_member;
	}

	nsgrp = __sgr_dup (sgrp);
	if (NULL == nsgrp) {
		fprintf (stderr,
			 _("%s: Out of memory. Cannot update %s.\n"),
			 Prog, sgr_dbname ());
		fail_exit (E_GRP_UPDATE);
	}

	if (was_admin && lflg) {
		/* User was an admin of this group but the user
		 * has been renamed.
		 */
		nsgrp->sg_adm = del_list (nsgrp->sg_adm, user_name);
		nsgrp->sg_adm = add_list (nsgrp->sg_adm, user_newname);
		changed = true;
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
			      "changing admin name in shadow group",
			      user_name, AUDIT_NO_ID, 1);
#endif
		SYSLOG ((LOG_INFO,
			 "change admin '%s' to '%s' in shadow group '%s'",
			 user_name, user_newname, nsgrp->sg_name));
	}

	if (was_member) {
		if ((!Gflg) || is_member) {
			/* User was a member and is still a member
			 * of this group.
			 * But the user might have been renamed.
			 */
			if (lflg) {
				nsgrp->sg_mem = del_list (nsgrp->sg_mem,
							  user_name);
				nsgrp->sg_mem = add_list (nsgrp->sg_mem,
							  user_newname);
				changed = true;
#ifdef WITH_AUDIT
				audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
					      "changing member in shadow group",
					      user_name, AUDIT_NO_ID, 1);
#endif
				SYSLOG ((LOG_INFO,
					 "change '%s' to '%s' in shadow group '%s'",
					 user_name, user_newname,
					 nsgrp->sg_name));
			}
		} else {
			/* User was a member but is no more a
			 * member of this group.
			 */
			nsgrp->sg_mem = del_list (nsgrp->sg_mem, user_name);
			changed = true;
#ifdef WITH_AUDIT
			audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
				      "removing user from shadow group",
				      user_name, AUDIT_NO_ID, 1);
#endif
			SYSLOG ((LOG_INFO,
				 "delete '%s' from shadow group '%s'",
				 user_name, nsgrp->sg_name));
		}
	} else if (is_member) {
		/* User was not a member but is now a member this
		 * group.
		 */
		nsgrp->sg_mem = add_list (nsgrp->sg_mem, user_newname);
		changed = true;
#ifdef WITH_AUDIT
		audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
			      "adding user to shadow group",
			      user_newname, AUDIT_NO_ID, 1);
#endif
		SYSLOG ((LOG_INFO, "add '%s' to shadow group '%s'",
			 user_newname, nsgrp->sg_name));
	}
	if (!changed)
		goto free_nsgrp;

	/*
	 * Update the group entry to reflect the changes.
	 */
	if (sgr_update (nsgrp) == 0) {
		fprintf (stderr,
			 _("%s: failed to prepare the new %s entry '%s'\n"),
			 Prog, sgr_dbname (), nsgrp->sg_name);
		SYSLOG ((LOG_WARN, "failed to prepare the new %s entry '%s'",
			 sgr_dbname (), nsgrp->sg_name));
		fail_exit (E_GRP_UPDATE);
	}

free_nsgrp:
	free (nsgrp);
}
#endif				/* SHADOWGRP */


/*
 * grp_update - add user to secondary group set
 *
 *	grp_update() takes the secondary group set given in user_groups and
 *	adds the user to each group given by that set.
 */
static void grp_update (void)
{
	update_group_file();
#ifdef SHADOWGRP
	if (is_shadow_grp) {
		update_gshadow_file();
	}
#endif
}

/*
 * process_flags - perform command line argument setting
 *
 *	process_flags() interprets the command line arguments and sets the
 *	values that the user will be created with accordingly. The values
 *	are checked for sanity.
 */
static void process_flags (int argc, char **argv)
{
	struct stat st;
	bool anyflag = false;

	{
		/*
		 * Parse the command line options.
		 */
		int c;
		static struct option long_options[] = {
			{"append",       no_argument,       NULL, 'a'},
			{"badname",      no_argument,       NULL, 'b'},
			{"badnames",     no_argument,       NULL, 'b'},
			{"comment",      required_argument, NULL, 'c'},
			{"home",         required_argument, NULL, 'd'},
			{"expiredate",   required_argument, NULL, 'e'},
			{"inactive",     required_argument, NULL, 'f'},
			{"gid",          required_argument, NULL, 'g'},
			{"groups",       required_argument, NULL, 'G'},
			{"help",         no_argument,       NULL, 'h'},
			{"login",        required_argument, NULL, 'l'},
			{"lock",         no_argument,       NULL, 'L'},
			{"move-home",    no_argument,       NULL, 'm'},
			{"non-unique",   no_argument,       NULL, 'o'},
			{"password",     required_argument, NULL, 'p'},
			{"remove",       no_argument,       NULL, 'r'},
			{"root",         required_argument, NULL, 'R'},
			{"prefix",       required_argument, NULL, 'P'},
			{"shell",        required_argument, NULL, 's'},
			{"uid",          required_argument, NULL, 'u'},
			{"unlock",       no_argument,       NULL, 'U'},
#ifdef ENABLE_SUBIDS
			{"add-subuids",  required_argument, NULL, 'v'},
			{"del-subuids",  required_argument, NULL, 'V'},
			{"add-subgids",  required_argument, NULL, 'w'},
			{"del-subgids",  required_argument, NULL, 'W'},
#endif				/* ENABLE_SUBIDS */
#ifdef WITH_SELINUX
			{"selinux-user",  required_argument, NULL, 'Z'},
			{"selinux-range", required_argument, NULL, 202},
#endif				/* WITH_SELINUX */
			{NULL, 0, NULL, '\0'}
		};
		while ((c = getopt_long (argc, argv,
		                         "abc:d:e:f:g:G:hl:Lmop:rR:s:u:UP:"
#ifdef ENABLE_SUBIDS
		                         "v:w:V:W:"
#endif				/* ENABLE_SUBIDS */
#ifdef WITH_SELINUX
			                 "Z:"
#endif				/* WITH_SELINUX */
			                 , long_options, NULL)) != -1) {
			switch (c) {
			case 'a':
				aflg = true;
				break;
			case 'b':
				allow_bad_names = true;
				break;
			case 'c':
				if (!VALID (optarg)) {
					fprintf (stderr,
					         _("%s: invalid field '%s'\n"),
					         Prog, optarg);
					exit (E_BAD_ARG);
				}
				user_newcomment = optarg;
				cflg = true;
				break;
			case 'd':
				if (!VALID (optarg)) {
					fprintf (stderr,
					         _("%s: invalid field '%s'\n"),
					         Prog, optarg);
					exit (E_BAD_ARG);
				}
				dflg = true;
				user_newhome = optarg;
				if (user_newhome[0] != '/') {
					fprintf (stderr,
					         _("%s: homedir must be an absolute path\n"),
					         Prog);
					exit (E_BAD_ARG);
				}
				break;
			case 'e':
				user_newexpire = strtoday (optarg);
				if (user_newexpire < -1) {
					fprintf (stderr,
						 _("%s: invalid date '%s'\n"),
						 Prog, optarg);
					exit (E_BAD_ARG);
				}
				eflg = true;
				break;
			case 'f':
				if (   (str2sl(&user_newinactive, optarg) == -1)
				    || (user_newinactive < -1)) {
					fprintf (stderr,
					         _("%s: invalid numeric argument '%s'\n"),
					         Prog, optarg);
					exit (E_BAD_ARG);
				}
				fflg = true;
				break;
			case 'g':
			{
				struct group  *grp;

				grp = prefix_getgr_nam_gid (optarg);
				if (NULL == grp) {
					fprintf (stderr,
					         _("%s: group '%s' does not exist\n"),
					         Prog, optarg);
					exit (E_NOTFOUND);
				}
				user_newgid = grp->gr_gid;
				gflg = true;
				gr_free (grp);
				break;
			}
			case 'G':
				if (get_groups (optarg) != 0) {
					exit (E_NOTFOUND);
				}
				Gflg = true;
				break;
			case 'h':
				usage (E_SUCCESS);
				/*@notreached@*/break;
			case 'l':
				if (!is_valid_user_name (optarg)) {
					fprintf (stderr,
					         _("%s: invalid user name '%s': use --badname to ignore\n"),
					         Prog, optarg);
					exit (E_BAD_ARG);
				}
				lflg = true;
				user_newname = optarg;
				break;
			case 'L':
				Lflg = true;
				break;
			case 'm':
				mflg = true;
				break;
			case 'o':
				oflg = true;
				break;
			case 'p':
				user_pass = optarg;
				pflg = true;
				break;
			case 'r':
				rflg = true;
				break;
			case 'R': /* no-op, handled in process_root_flag () */
				break;
			case 'P': /* no-op, handled in process_prefix_flag () */
				break;
			case 's':
				if (   ( !VALID (optarg) )
				    || (   ('\0' != optarg[0])
				        && ('/'  != optarg[0])
				        && ('*'  != optarg[0]) )) {
					fprintf (stderr,
					         _("%s: invalid shell '%s'\n"),
					         Prog, optarg);
					exit (E_BAD_ARG);
				}
				if (    '\0' != optarg[0]
				     && '*'  != optarg[0]
				     && strcmp(optarg, "/sbin/nologin") != 0
				     && (   stat(optarg, &st) != 0
				         || S_ISDIR(st.st_mode)
				         || access(optarg, X_OK) != 0)) {
					fprintf (stderr,
					         _("%s: Warning: missing or non-executable shell '%s'\n"),
					         Prog, optarg);
				}
				user_newshell = optarg;
				sflg = true;
				break;
			case 'u':
				if (   (get_uid(optarg, &user_newid) == -1)
				    || (user_newid == (uid_t)-1)) {
					fprintf (stderr,
					         _("%s: invalid user ID '%s'\n"),
					         Prog, optarg);
					exit (E_BAD_ARG);
				}
				uflg = true;
				break;
			case 'U':
				Uflg = true;
				break;
#ifdef ENABLE_SUBIDS
			case 'v':
				if (prepend_range (optarg, &add_sub_uids) == 0) {
					fprintf (stderr,
						_("%s: invalid subordinate uid range '%s'\n"),
						Prog, optarg);
					exit(E_BAD_ARG);
				}
				vflg = true;
				break;
			case 'V':
				if (prepend_range (optarg, &del_sub_uids) == 0) {
					fprintf (stderr,
						_("%s: invalid subordinate uid range '%s'\n"),
						Prog, optarg);
					exit(E_BAD_ARG);
				}
				Vflg = true;
				break;
			case 'w':
				if (prepend_range (optarg, &add_sub_gids) == 0) {
					fprintf (stderr,
						_("%s: invalid subordinate gid range '%s'\n"),
						Prog, optarg);
					exit(E_BAD_ARG);
				}
				wflg = true;
                break;
			case 'W':
				if (prepend_range (optarg, &del_sub_gids) == 0) {
					fprintf (stderr,
						_("%s: invalid subordinate gid range '%s'\n"),
						Prog, optarg);
					exit(E_BAD_ARG);
				}
				Wflg = true;
				break;
#endif				/* ENABLE_SUBIDS */
#ifdef WITH_SELINUX
			case 'Z':
				if (prefix[0]) {
					fprintf (stderr,
					         _("%s: -Z cannot be used with --prefix\n"),
					         Prog);
					exit (E_BAD_ARG);
				}
				if (is_selinux_enabled () > 0) {
					user_selinux = optarg;
					Zflg = true;
				} else {
					fprintf (stderr,
					         _("%s: -Z requires SELinux enabled kernel\n"),
					         Prog);
					exit (E_BAD_ARG);
				}
				break;
			case 202:
				user_selinux_range = optarg;
				break;
#endif				/* WITH_SELINUX */
			default:
				usage (E_USAGE);
			}
			anyflag = true;
		}
	}

	if (optind != argc - 1) {
		usage (E_USAGE);
	}

	user_name = argv[argc - 1];

	{
		const struct passwd *pwd;
		/* local, no need for xgetpwnam */
		pwd = prefix_getpwnam (user_name);
		if (NULL == pwd) {
			fprintf (stderr,
			         _("%s: user '%s' does not exist\n"),
			         Prog, user_name);
			exit (E_NOTFOUND);
		}

		user_id = pwd->pw_uid;
		user_gid = pwd->pw_gid;
		user_comment = xstrdup (pwd->pw_gecos);
		user_home = xstrdup (pwd->pw_dir);
		user_shell = xstrdup (pwd->pw_shell);
	}

	/* user_newname, user_newid, user_newgid can be used even when the
	 * options where not specified. */
	if (!lflg) {
		user_newname = user_name;
	}
	if (!uflg) {
		user_newid = user_id;
	}
	if (!gflg) {
		user_newgid = user_gid;
	}
	if (prefix[0]) {
		xasprintf(&prefix_user_home, "%s/%s", prefix, user_home);
		if (user_newhome) {
			xasprintf(&prefix_user_newhome, "%s/%s",
			          prefix, user_newhome);
		}
	} else {
		prefix_user_home = user_home;
		prefix_user_newhome = user_newhome;
	}

	{
		const struct spwd *spwd = NULL;
		/* local, no need for xgetspnam */
		if (is_shadow_pwd && ((spwd = prefix_getspnam (user_name)) != NULL)) {
			user_expire = spwd->sp_expire;
			user_inactive = spwd->sp_inact;
		}
	}

	if (!anyflag) {
		fprintf (stderr, _("%s: no options\n"), Prog);
		usage (E_USAGE);
	}

	if (aflg && (!Gflg)) {
		fprintf (stderr,
		         _("%s: %s flag is only allowed with the %s flag\n"),
		         Prog, "-a", "-G");
		usage (E_USAGE);
	}

	if (rflg && (!Gflg)) {
		fprintf (stderr,
		         _("%s: %s flag is only allowed with the %s flag\n"),
		         Prog, "-r", "-G");
		usage (E_USAGE);
	}

	if (rflg && aflg) {
		fprintf (stderr,
		         _("%s: %s and %s are mutually exclusive flags\n"),
		         Prog, "-r", "-a");
		usage (E_USAGE);
	}

	if ((Lflg && (pflg || Uflg)) || (pflg && Uflg)) {
		fprintf (stderr,
		         _("%s: the -L, -p, and -U flags are exclusive\n"),
		         Prog);
		usage (E_USAGE);
	}

	if (oflg && !uflg) {
		fprintf (stderr,
		         _("%s: %s flag is only allowed with the %s flag\n"),
		         Prog, "-o", "-u");
		usage (E_USAGE);
	}

	if (mflg && !dflg) {
		fprintf (stderr,
		         _("%s: %s flag is only allowed with the %s flag\n"),
		         Prog, "-m", "-d");
		usage (E_USAGE);
	}

#ifdef WITH_SELINUX
	if (user_selinux_range && !Zflg) {
		fprintf (stderr,
		         _("%s: %s flag is only allowed with the %s flag\n"),
		         Prog, "--selinux-range", "--selinux-user");
		usage (E_USAGE);
	}
#endif				/* WITH_SELINUX */

	if (user_newid == user_id) {
		uflg = false;
		oflg = false;
	}
	if (user_newgid == user_gid) {
		gflg = false;
	}
	if (   (NULL != user_newshell)
	    && (strcmp (user_newshell, user_shell) == 0)) {
		sflg = false;
	}
	if (strcmp (user_newname, user_name) == 0) {
		lflg = false;
	}
	if (user_newinactive == user_inactive) {
		fflg = false;
	}
	if (user_newexpire == user_expire) {
		eflg = false;
	}
	if (   (NULL != user_newhome)
	    && (strcmp (user_newhome, user_home) == 0)) {
		dflg = false;
		mflg = false;
	}
	if (   (NULL != user_newcomment)
	    && (strcmp (user_newcomment, user_comment) == 0)) {
		cflg = false;
	}

	if (!(Uflg || uflg || sflg || pflg || mflg || Lflg ||
	      lflg || Gflg || gflg || fflg || eflg || dflg || cflg
#ifdef ENABLE_SUBIDS
	      || vflg || Vflg || wflg || Wflg
#endif				/* ENABLE_SUBIDS */
#ifdef WITH_SELINUX
	      || Zflg
#endif				/* WITH_SELINUX */
	)) {
		fprintf (stdout, _("%s: no changes\n"), Prog);
		exit (E_SUCCESS);
	}

	if (!is_shadow_pwd && (eflg || fflg)) {
		fprintf (stderr,
		         _("%s: shadow passwords required for -e and -f\n"),
		         Prog);
		exit (E_USAGE);
	}

	/* local, no need for xgetpwnam */
	if (lflg && (prefix_getpwnam (user_newname) != NULL)) {
		fprintf (stderr,
		         _("%s: user '%s' already exists\n"),
		         Prog, user_newname);
		exit (E_NAME_IN_USE);
	}

	/* local, no need for xgetpwuid */
	if (uflg && !oflg && (prefix_getpwuid (user_newid) != NULL)) {
		fprintf (stderr,
		         _("%s: UID '%lu' already exists\n"),
		         Prog, (unsigned long) user_newid);
		exit (E_UID_IN_USE);
	}

#ifdef ENABLE_SUBIDS
	if (   (vflg || Vflg)
	    && !is_sub_uid) {
		fprintf (stderr,
		         _("%s: %s does not exist, you cannot use the flags %s or %s\n"),
		         Prog, sub_uid_dbname (), "-v", "-V");
		exit (E_USAGE);
	}

	if (   (wflg || Wflg)
	    && !is_sub_gid) {
		fprintf (stderr,
		         _("%s: %s does not exist, you cannot use the flags %s or %s\n"),
		         Prog, sub_gid_dbname (), "-w", "-W");
		exit (E_USAGE);
	}
#endif				/* ENABLE_SUBIDS */
}

/*
 * close_files - close all of the files that were opened
 *
 *	close_files() closes all of the files that were opened for this new
 *	user. This causes any modified entries to be written out.
 */
static void close_files (void)
{
	if (pw_close () == 0) {
		fprintf (stderr,
		         _("%s: failure while writing changes to %s\n"),
		         Prog, pw_dbname ());
		SYSLOG ((LOG_ERR, "failure while writing changes to %s", pw_dbname ()));
		fail_exit (E_PW_UPDATE);
	}
	if (is_shadow_pwd && (spw_close () == 0)) {
		fprintf (stderr,
		         _("%s: failure while writing changes to %s\n"),
		         Prog, spw_dbname ());
		SYSLOG ((LOG_ERR,
		         "failure while writing changes to %s",
		         spw_dbname ()));
		fail_exit (E_PW_UPDATE);
	}

	if (Gflg || lflg) {
		if (gr_close () == 0) {
			fprintf (stderr,
			         _("%s: failure while writing changes to %s\n"),
			         Prog, gr_dbname ());
			SYSLOG ((LOG_ERR,
			         "failure while writing changes to %s",
			         gr_dbname ()));
			fail_exit (E_GRP_UPDATE);
		}
#ifdef SHADOWGRP
		if (is_shadow_grp) {
			if (sgr_close () == 0) {
				fprintf (stderr,
				         _("%s: failure while writing changes to %s\n"),
				         Prog, sgr_dbname ());
				SYSLOG ((LOG_ERR,
				         "failure while writing changes to %s",
				         sgr_dbname ()));
				fail_exit (E_GRP_UPDATE);
			}
		}
#endif
#ifdef SHADOWGRP
		if (is_shadow_grp) {
			if (sgr_unlock () == 0) {
				fprintf (stderr,
				         _("%s: failed to unlock %s\n"),
				         Prog, sgr_dbname ());
				SYSLOG ((LOG_ERR,
				         "failed to unlock %s",
				         sgr_dbname ()));
				/* continue */
			}
		}
#endif
		if (gr_unlock () == 0) {
			fprintf (stderr,
			         _("%s: failed to unlock %s\n"),
			         Prog, gr_dbname ());
			SYSLOG ((LOG_ERR,
			         "failed to unlock %s",
			         gr_dbname ()));
			/* continue */
		}
	}

	if (is_shadow_pwd) {
		if (spw_unlock () == 0) {
			fprintf (stderr,
			         _("%s: failed to unlock %s\n"),
			         Prog, spw_dbname ());
			SYSLOG ((LOG_ERR,
			         "failed to unlock %s",
			         spw_dbname ()));
			/* continue */
		}
	}
	if (pw_unlock () == 0) {
		fprintf (stderr,
		         _("%s: failed to unlock %s\n"),
		         Prog, pw_dbname ());
		SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
		/* continue */
	}

	pw_locked = false;
	spw_locked = false;
	gr_locked = false;
#ifdef	SHADOWGRP
	sgr_locked = false;
#endif

#ifdef ENABLE_SUBIDS
	if (vflg || Vflg) {
		if (sub_uid_close () == 0) {
			fprintf (stderr, _("%s: failure while writing changes to %s\n"), Prog, sub_uid_dbname ());
			SYSLOG ((LOG_ERR, "failure while writing changes to %s", sub_uid_dbname ()));
			fail_exit (E_SUB_UID_UPDATE);
		}
		if (sub_uid_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sub_uid_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", sub_uid_dbname ()));
			/* continue */
		}
		sub_uid_locked = false;
	}
	if (wflg || Wflg) {
		if (sub_gid_close () == 0) {
			fprintf (stderr, _("%s: failure while writing changes to %s\n"), Prog, sub_gid_dbname ());
			SYSLOG ((LOG_ERR, "failure while writing changes to %s", sub_gid_dbname ()));
			fail_exit (E_SUB_GID_UPDATE);
		}
		if (sub_gid_unlock () == 0) {
			fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sub_gid_dbname ());
			SYSLOG ((LOG_ERR, "failed to unlock %s", sub_gid_dbname ()));
			/* continue */
		}
		sub_gid_locked = false;
	}
#endif				/* ENABLE_SUBIDS */

	/*
	 * Close the DBM and/or flat files
	 */
	endpwent ();
	endspent ();
	endgrent ();
#ifdef	SHADOWGRP
	endsgent ();
#endif
}

/*
 * open_files - lock and open the password files
 *
 *	open_files() opens the two password files.
 */
static void open_files (void)
{
	if (pw_lock () == 0) {
		fprintf (stderr,
		         _("%s: cannot lock %s; try again later.\n"),
		         Prog, pw_dbname ());
		fail_exit (E_PW_UPDATE);
	}
	pw_locked = true;
	if (pw_open (O_CREAT | O_RDWR) == 0) {
		fprintf (stderr,
		         _("%s: cannot open %s\n"),
		         Prog, pw_dbname ());
		fail_exit (E_PW_UPDATE);
	}
	if (is_shadow_pwd && (spw_lock () == 0)) {
		fprintf (stderr,
		         _("%s: cannot lock %s; try again later.\n"),
		         Prog, spw_dbname ());
		fail_exit (E_PW_UPDATE);
	}
	spw_locked = true;
	if (is_shadow_pwd && (spw_open (O_CREAT | O_RDWR) == 0)) {
		fprintf (stderr,
		         _("%s: cannot open %s\n"),
		         Prog, spw_dbname ());
		fail_exit (E_PW_UPDATE);
	}

	if (Gflg || lflg) {
		/*
		 * Lock and open the group file. This will load all of the
		 * group entries.
		 */
		if (gr_lock () == 0) {
			fprintf (stderr,
			         _("%s: cannot lock %s; try again later.\n"),
			         Prog, gr_dbname ());
			fail_exit (E_GRP_UPDATE);
		}
		gr_locked = true;
		if (gr_open (O_CREAT | O_RDWR) == 0) {
			fprintf (stderr,
			         _("%s: cannot open %s\n"),
			         Prog, gr_dbname ());
			fail_exit (E_GRP_UPDATE);
		}
#ifdef SHADOWGRP
		if (is_shadow_grp && (sgr_lock () == 0)) {
			fprintf (stderr,
			         _("%s: cannot lock %s; try again later.\n"),
			         Prog, sgr_dbname ());
			fail_exit (E_GRP_UPDATE);
		}
		sgr_locked = true;
		if (is_shadow_grp && (sgr_open (O_CREAT | O_RDWR) == 0)) {
			fprintf (stderr,
			         _("%s: cannot open %s\n"),
			         Prog, sgr_dbname ());
			fail_exit (E_GRP_UPDATE);
		}
#endif
	}
#ifdef ENABLE_SUBIDS
	if (vflg || Vflg) {
		if (sub_uid_lock () == 0) {
			fprintf (stderr,
			         _("%s: cannot lock %s; try again later.\n"),
			         Prog, sub_uid_dbname ());
			fail_exit (E_SUB_UID_UPDATE);
		}
		sub_uid_locked = true;
		if (sub_uid_open (O_CREAT | O_RDWR) == 0) {
			fprintf (stderr,
			         _("%s: cannot open %s\n"),
			         Prog, sub_uid_dbname ());
			fail_exit (E_SUB_UID_UPDATE);
		}
	}
	if (wflg || Wflg) {
		if (sub_gid_lock () == 0) {
			fprintf (stderr,
			         _("%s: cannot lock %s; try again later.\n"),
			         Prog, sub_gid_dbname ());
			fail_exit (E_SUB_GID_UPDATE);
		}
		sub_gid_locked = true;
		if (sub_gid_open (O_CREAT | O_RDWR) == 0) {
			fprintf (stderr,
			         _("%s: cannot open %s\n"),
			         Prog, sub_gid_dbname ());
			fail_exit (E_SUB_GID_UPDATE);
		}
	}
#endif				/* ENABLE_SUBIDS */
}

/*
 * usr_update - create the user entries
 *
 *	usr_update() creates the password file entries for this user and
 *	will update the group entries if required.
 */
static void usr_update (void)
{
	struct passwd pwent;
	const struct passwd *pwd;

	struct spwd spent;
	const struct spwd *spwd = NULL;

	/*
	 * Locate the entry in /etc/passwd, which MUST exist.
	 */
	pwd = pw_locate (user_name);
	if (NULL == pwd) {
		fprintf (stderr,
		         _("%s: user '%s' does not exist in %s\n"),
		         Prog, user_name, pw_dbname ());
		fail_exit (E_NOTFOUND);
	}
	pwent = *pwd;
	new_pwent (&pwent);


	/* If the shadow file does not exist, it won't be created */
	if (is_shadow_pwd) {
		spwd = spw_locate (user_name);
		if (NULL != spwd) {
			/* Update the shadow entry if it exists */
			spent = *spwd;
			new_spent (&spent);
		} else if (   (    pflg
		               && (strcmp (pwent.pw_passwd, SHADOW_PASSWD_STRING) == 0))
		           || eflg || fflg) {
			/* In some cases, we force the creation of a
			 * shadow entry:
			 *  + new password requested and passwd indicates
			 *    a shadowed password
			 *  + aging information is requested
			 */
			bzero(&spent, sizeof spent);
			spent.sp_namp   = user_name;

			/* The user explicitly asked for a shadow feature.
			 * Enable shadowed passwords for this new account.
			 */
			spent.sp_pwdp   = xstrdup (pwent.pw_passwd);
			pwent.pw_passwd = xstrdup (SHADOW_PASSWD_STRING);

			spent.sp_lstchg = gettime () / DAY;
			if (0 == spent.sp_lstchg) {
				/* Better disable aging than
				 * requiring a password change */
				spent.sp_lstchg = -1;
			}
			spent.sp_min    = getdef_num ("PASS_MIN_DAYS", -1);
			spent.sp_max    = getdef_num ("PASS_MAX_DAYS", -1);
			spent.sp_warn   = getdef_num ("PASS_WARN_AGE", -1);
			spent.sp_inact  = -1;
			spent.sp_expire = -1;
			spent.sp_flag   = SHADOW_SP_FLAG_UNSET;
			new_spent (&spent);
			spwd = &spent; /* entry needs to be committed */
		}
	}

	if (lflg || uflg || gflg || cflg || dflg || sflg || pflg
	    || Lflg || Uflg) {
		if (pw_update (&pwent) == 0) {
			fprintf (stderr,
			         _("%s: failed to prepare the new %s entry '%s'\n"),
			         Prog, pw_dbname (), pwent.pw_name);
			fail_exit (E_PW_UPDATE);
		}
		if (lflg && (pw_remove (user_name) == 0)) {
			fprintf (stderr,
			         _("%s: cannot remove entry '%s' from %s\n"),
			         Prog, user_name, pw_dbname ());
			fail_exit (E_PW_UPDATE);
		}
	}
	if ((NULL != spwd) && (lflg || eflg || fflg || pflg || Lflg || Uflg)) {
		if (spw_update (&spent) == 0) {
			fprintf (stderr,
			         _("%s: failed to prepare the new %s entry '%s'\n"),
			         Prog, spw_dbname (), spent.sp_namp);
			fail_exit (E_PW_UPDATE);
		}
		if (lflg && (spw_remove (user_name) == 0)) {
			fprintf (stderr,
			         _("%s: cannot remove entry '%s' from %s\n"),
			         Prog, user_name, spw_dbname ());
			fail_exit (E_PW_UPDATE);
		}
	}
}

/*
 * move_home - move the user's home directory
 *
 *	move_home() moves the user's home directory to a new location. The
 *	files will be copied if the directory cannot simply be renamed.
 */
static void move_home (void)
{
	struct stat sb;

	if (access (prefix_user_newhome, F_OK) == 0) {
		/*
		 * If the new home directory already exist, the user
		 * should not use -m.
		 */
		fprintf (stderr,
		         _("%s: directory %s exists\n"),
		         Prog, user_newhome);
		fail_exit (E_HOMEDIR);
	}

	if (stat (prefix_user_home, &sb) == 0) {
		/*
		 * Don't try to move it if it is not a directory
		 * (but /dev/null for example).  --marekm
		 */
		if (!S_ISDIR (sb.st_mode)) {
			fprintf (stderr,
			         _("%s: The previous home directory (%s) was "
			           "not a directory. It is not removed and no "
			           "home directories are created.\n"),
			         Prog, user_home);
			fail_exit (E_HOMEDIR);
		}

#ifdef WITH_AUDIT
		if (uflg || gflg) {
			audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
				      "changing home directory owner",
				      user_newname, user_newid, 1);
		}
#endif

		if (rename (prefix_user_home, prefix_user_newhome) == 0) {
			/* FIXME: rename above may have broken symlinks
			 *        pointing to the user's home directory
			 *        with an absolute path. */
			if (chown_tree (prefix_user_newhome,
			                user_id,  uflg ? user_newid  : (uid_t)-1,
			                user_gid, gflg ? user_newgid : (gid_t)-1) != 0) {
				fprintf (stderr,
				         _("%s: Failed to change ownership of the home directory"),
				         Prog);
				fail_exit (E_HOMEDIR);
			}
#ifdef WITH_AUDIT
			audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
			              "moving home directory",
			              user_newname, user_newid, 1);
#endif
			return;
		} else {
			if (EXDEV == errno) {
#ifdef WITH_BTRFS
				if (btrfs_is_subvolume (prefix_user_home) > 0) {
					fprintf (stderr,
					        _("%s: error: cannot move subvolume from %s to %s - different device\n"),
					        Prog, prefix_user_home, prefix_user_newhome);
					fail_exit (E_HOMEDIR);
				}
#endif

				if (copy_tree (prefix_user_home, prefix_user_newhome, true,
				               true,
				               user_id,
				               uflg ? user_newid : (uid_t)-1,
				               user_gid,
				               gflg ? user_newgid : (gid_t)-1) == 0) {
					if (remove_tree (prefix_user_home, true) != 0) {
						fprintf (stderr,
						         _("%s: warning: failed to completely remove old home directory %s"),
						         Prog, prefix_user_home);
					}
#ifdef WITH_AUDIT
					audit_logger (AUDIT_USER_CHAUTHTOK,
					              Prog,
					              "moving home directory",
					              user_newname,
					              user_newid,
					              1);
#endif
					return;
				}

				(void) remove_tree (prefix_user_newhome, true);
			}
			fprintf (stderr,
			         _("%s: cannot rename directory %s to %s\n"),
			         Prog, prefix_user_home, prefix_user_newhome);
			fail_exit (E_HOMEDIR);
		}
	} else {
		fprintf (stderr,
		         _("%s: The previous home directory (%s) does not "
		           "exist or is inaccessible. Move cannot be completed.\n"),
		         Prog, prefix_user_home);
	}
}

/*
 * update_lastlog - update the lastlog file
 *
 * Relocate the "lastlog" entries for the user. The old entry is
 * left alone in case the UID was shared. It doesn't hurt anything
 * to just leave it be.
 */
#ifdef ENABLE_LASTLOG
static void update_lastlog (void)
{
	struct lastlog ll;
	int fd;
	off_t off_uid = (off_t) user_id * sizeof ll;
	off_t off_newuid = (off_t) user_newid * sizeof ll;
	uid_t max_uid;

	if (access (LASTLOG_FILE, F_OK) != 0) {
		return;
	}

	max_uid = getdef_ulong ("LASTLOG_UID_MAX", 0xFFFFFFFFUL);
	if (user_newid > max_uid) {
		/* do not touch lastlog for large uids */
		return;
	}

	fd = open (LASTLOG_FILE, O_RDWR);

	if (-1 == fd) {
		fprintf (stderr,
		         _("%s: failed to copy the lastlog entry of user %lu to user %lu: %s\n"),
		         Prog, (unsigned long) user_id, (unsigned long) user_newid, strerror (errno));
		return;
	}

	if (   (lseek (fd, off_uid, SEEK_SET) == off_uid)
	    && (read (fd, &ll, sizeof ll) == (ssize_t) sizeof ll)) {
		/* Copy the old entry to its new location */
		if (   (lseek (fd, off_newuid, SEEK_SET) != off_newuid)
		    || (write_full(fd, &ll, sizeof ll) == -1)
		    || (fsync (fd) != 0)) {
			fprintf (stderr,
			         _("%s: failed to copy the lastlog entry of user %lu to user %lu: %s\n"),
			         Prog, (unsigned long) user_id, (unsigned long) user_newid, strerror (errno));
		}
	} else {
		/* Assume lseek or read failed because there is
		 * no entry for the old UID */

		/* Check if the new UID already has an entry */
		if (   (lseek (fd, off_newuid, SEEK_SET) == off_newuid)
		    && (read (fd, &ll, sizeof ll) == (ssize_t) sizeof ll)) {
			/* Reset the new uid's lastlog entry */
			memzero (&ll, sizeof (ll));
			if (   (lseek (fd, off_newuid, SEEK_SET) != off_newuid)
			    || (write_full(fd, &ll, sizeof ll) == -1)
			    || (fsync (fd) != 0)) {
				fprintf (stderr,
				         _("%s: failed to copy the lastlog entry of user %lu to user %lu: %s\n"),
				         Prog, (unsigned long) user_id, (unsigned long) user_newid, strerror (errno));
			}
		}
	}

	if (close (fd) != 0 && errno != EINTR) {
		fprintf (stderr,
		         _("%s: failed to copy the lastlog entry of user %ju to user %ju: %s\n"),
		         Prog, (uintmax_t) user_id, (uintmax_t) user_newid, strerror (errno));
	}
}
#endif /* ENABLE_LASTLOG */

/*
 * update_faillog - update the faillog file
 *
 * Relocate the "faillog" entries for the user. The old entry is
 * left alone in case the UID was shared. It doesn't hurt anything
 * to just leave it be.
 */
static void update_faillog (void)
{
	struct faillog fl;
	int fd;
	off_t off_uid = (off_t) user_id * sizeof fl;
	off_t off_newuid = (off_t) user_newid * sizeof fl;

	if (access (FAILLOG_FILE, F_OK) != 0) {
		return;
	}

	fd = open (FAILLOG_FILE, O_RDWR);

	if (-1 == fd) {
		fprintf (stderr,
		         _("%s: failed to copy the faillog entry of user %lu to user %lu: %s\n"),
		         Prog, (unsigned long) user_id, (unsigned long) user_newid, strerror (errno));
		return;
	}

	if (   (lseek (fd, off_uid, SEEK_SET) == off_uid)
	    && (read (fd, &fl, sizeof fl) == (ssize_t) sizeof fl)) {
		/* Copy the old entry to its new location */
		if (   (lseek (fd, off_newuid, SEEK_SET) != off_newuid)
		    || (write_full(fd, &fl, sizeof fl) == -1)
		    || (fsync (fd) != 0)) {
			fprintf (stderr,
			         _("%s: failed to copy the faillog entry of user %lu to user %lu: %s\n"),
			         Prog, (unsigned long) user_id, (unsigned long) user_newid, strerror (errno));
		}
	} else {
		/* Assume lseek or read failed because there is
		 * no entry for the old UID */

		/* Check if the new UID already has an entry */
		if (   (lseek (fd, off_newuid, SEEK_SET) == off_newuid)
		    && (read (fd, &fl, sizeof fl) == (ssize_t) sizeof fl)) {
			/* Reset the new uid's faillog entry */
			memzero (&fl, sizeof (fl));
			if (   (lseek (fd, off_newuid, SEEK_SET) != off_newuid)
			    || (write_full(fd, &fl, sizeof fl) == -1))
			{
				fprintf (stderr,
				         _("%s: failed to copy the faillog entry of user %lu to user %lu: %s\n"),
				         Prog, (unsigned long) user_id, (unsigned long) user_newid, strerror (errno));
			}
		}
	}

	if (close (fd) != 0 && errno != EINTR) {
		fprintf (stderr,
		         _("%s: failed to copy the faillog entry of user %ju to user %ju: %s\n"),
		         Prog, (uintmax_t) user_id, (uintmax_t) user_newid, strerror (errno));
	}
}

#ifndef NO_MOVE_MAILBOX
/*
 * This is the new and improved code to carefully chown/rename the user's
 * mailbox. Maybe I am too paranoid but the mail spool dir sometimes
 * happens to be mode 1777 (this makes mail user agents work without
 * being setgid mail, but is NOT recommended; they all should be fixed
 * to use movemail).  --marekm
 */
static void move_mailbox (void)
{
	int          fd;
	char         *mailfile;
	const char   *maildir;
	struct stat  st;

	maildir = getdef_str ("MAIL_DIR");
#ifdef MAIL_SPOOL_DIR
	if ((NULL == maildir) && (getdef_str ("MAIL_FILE") == NULL)) {
		maildir = MAIL_SPOOL_DIR;
	}
#endif
	if (NULL == maildir) {
		return;
	}

	/*
	 * O_NONBLOCK is to make sure open won't hang on mandatory locks.
	 * We do fstat/fchown to make sure there are no races (someone
	 * replacing /var/spool/mail/luser with a hard link to /etc/passwd
	 * between stat and chown).  --marekm
	 */
	if (prefix[0]) {
		xasprintf(&mailfile, "%s/%s/%s", prefix, maildir, user_name);
	} else {
		xasprintf(&mailfile, "%s/%s", maildir, user_name);
	}

	fd = open (mailfile, O_RDONLY | O_NONBLOCK, 0);
	if (fd < 0) {
		/* no need for warnings if the mailbox doesn't exist */
		if (errno != ENOENT) {
			perror (mailfile);
		}
		free(mailfile);
		return;
	}
	if (fstat (fd, &st) < 0) {
		perror ("fstat");
		(void) close (fd);
		free(mailfile);
		return;
	}
	if (st.st_uid != user_id) {
		/* better leave it alone */
		fprintf (stderr, _("%s: warning: %s not owned by %s\n"),
		         Prog, mailfile, user_name);
		(void) close (fd);
		free(mailfile);
		return;
	}
	if (uflg) {
		if (fchown (fd, user_newid, (gid_t) -1) < 0) {
			perror (_("failed to change mailbox owner"));
		}
#ifdef WITH_AUDIT
		else {
			audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
			              "changing mail file owner",
			              user_newname, user_newid, 1);
		}
#endif
	}

	(void) close (fd);

	if (lflg) {
		char  *newmailfile;

		if (prefix[0]) {
			xasprintf(&newmailfile, "%s/%s/%s",
			          prefix, maildir, user_newname);
		} else {
			xasprintf(&newmailfile, "%s/%s", maildir, user_newname);
		}
		if (   (link (mailfile, newmailfile) != 0)
		    || (unlink (mailfile) != 0)) {
			perror (_("failed to rename mailbox"));
		}
#ifdef WITH_AUDIT
		else {
			audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
			              "changing mail file name",
			              user_newname, user_newid, 1);
		}

		free(newmailfile);
#endif
	}

	free(mailfile);
}
#endif

/*
 * main - usermod command
 */
int main (int argc, char **argv)
{
#ifdef ACCT_TOOLS_SETUID
#ifdef USE_PAM
	pam_handle_t *pamh = NULL;
	int retval;
#endif				/* USE_PAM */
#endif				/* ACCT_TOOLS_SETUID */

	log_set_progname(Prog);
	log_set_logfd(stderr);

	(void) setlocale (LC_ALL, "");
	(void) bindtextdomain (PACKAGE, LOCALEDIR);
	(void) textdomain (PACKAGE);

	process_root_flag ("-R", argc, argv);
	prefix = process_prefix_flag ("-P", argc, argv);

	OPENLOG (Prog);
#ifdef WITH_AUDIT
	audit_help_open ();
#endif

	sys_ngroups = sysconf (_SC_NGROUPS_MAX);
	user_groups = XMALLOC(sys_ngroups + 1, char *);
	user_groups[0] = NULL;

	is_shadow_pwd = spw_file_present ();
#ifdef SHADOWGRP
	is_shadow_grp = sgr_file_present ();
#endif
#ifdef ENABLE_SUBIDS
	is_sub_uid = sub_uid_file_present ();
	is_sub_gid = sub_gid_file_present ();
#endif				/* ENABLE_SUBIDS */

	process_flags (argc, argv);

	/*
	 * The home directory, the username and the user's UID should not
	 * be changed while the user is logged in.
	 * Note: no need to check if a prefix is specified...
	 */
	if ( (prefix[0] == '\0') &&  (uflg || lflg || dflg
#ifdef ENABLE_SUBIDS
	        || Vflg || Wflg
#endif				/* ENABLE_SUBIDS */
	       )
	    && (user_busy (user_name, user_id) != 0)) {
		exit (E_USER_BUSY);
	}

#ifdef ACCT_TOOLS_SETUID
#ifdef USE_PAM
	{
		struct passwd *pampw;
		pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
		if (pampw == NULL) {
			fprintf (stderr,
			         _("%s: Cannot determine your user name.\n"),
			         Prog);
			exit (1);
		}

		retval = pam_start (Prog, pampw->pw_name, &conv, &pamh);
	}

	if (PAM_SUCCESS == retval) {
		retval = pam_authenticate (pamh, 0);
	}

	if (PAM_SUCCESS == retval) {
		retval = pam_acct_mgmt (pamh, 0);
	}

	if (PAM_SUCCESS != retval) {
		fprintf (stderr, _("%s: PAM: %s\n"),
		         Prog, pam_strerror (pamh, retval));
		SYSLOG((LOG_ERR, "%s", pam_strerror (pamh, retval)));
		if (NULL != pamh) {
			(void) pam_end (pamh, retval);
		}
		exit (1);
	}
	(void) pam_end (pamh, retval);
#endif				/* USE_PAM */
#endif				/* ACCT_TOOLS_SETUID */

#ifdef WITH_TCB
	if (shadowtcb_set_user (user_name) == SHADOWTCB_FAILURE) {
		exit (E_PW_UPDATE);
	}
#endif

	/*
	 * Do the hard stuff - open the files, change the user entries,
	 * change the home directory, then close and update the files.
	 */
	open_files ();
	if (   cflg || dflg || eflg || fflg || gflg || Lflg || lflg || pflg
	    || sflg || uflg || Uflg) {
		usr_update ();
	}
	if (Gflg || lflg) {
		grp_update ();
	}
#ifdef ENABLE_SUBIDS
	if (Vflg) {
		struct ulong_range_list_entry *ptr;
		for (ptr = del_sub_uids; ptr != NULL; ptr = ptr->next) {
			unsigned long count = ptr->range.last - ptr->range.first + 1;
			if (sub_uid_remove(user_name, ptr->range.first, count) == 0) {
				fprintf (stderr,
					_("%s: failed to remove uid range %lu-%lu from '%s'\n"),
					Prog, ptr->range.first, ptr->range.last,
					sub_uid_dbname ());
				fail_exit (E_SUB_UID_UPDATE);
			}
		}
	}
	if (vflg) {
		struct ulong_range_list_entry *ptr;
		for (ptr = add_sub_uids; ptr != NULL; ptr = ptr->next) {
			unsigned long count = ptr->range.last - ptr->range.first + 1;
			if (sub_uid_add(user_name, ptr->range.first, count) == 0) {
				fprintf (stderr,
					_("%s: failed to add uid range %lu-%lu to '%s'\n"),
					Prog, ptr->range.first, ptr->range.last,
					sub_uid_dbname ());
				fail_exit (E_SUB_UID_UPDATE);
			}
		}
	}
	if (Wflg) {
		struct ulong_range_list_entry *ptr;
		for (ptr = del_sub_gids; ptr != NULL; ptr = ptr->next) {
			unsigned long count = ptr->range.last - ptr->range.first + 1;
			if (sub_gid_remove(user_name, ptr->range.first, count) == 0) {
				fprintf (stderr,
					_("%s: failed to remove gid range %lu-%lu from '%s'\n"),
					Prog, ptr->range.first, ptr->range.last,
					sub_gid_dbname ());
				fail_exit (E_SUB_GID_UPDATE);
			}
		}
	}
	if (wflg) {
		struct ulong_range_list_entry *ptr;
		for (ptr = add_sub_gids; ptr != NULL; ptr = ptr->next) {
			unsigned long count = ptr->range.last - ptr->range.first + 1;
			if (sub_gid_add(user_name, ptr->range.first, count) == 0) {
				fprintf (stderr,
					_("%s: failed to add gid range %lu-%lu to '%s'\n"),
					Prog, ptr->range.first, ptr->range.last,
					sub_gid_dbname ());
				fail_exit (E_SUB_GID_UPDATE);
			}
		}
	}
#endif				/* ENABLE_SUBIDS */
	close_files ();

#ifdef WITH_TCB
	if (   (lflg || uflg)
	    && (shadowtcb_move (user_newname, user_newid) == SHADOWTCB_FAILURE) ) {
		exit (E_PW_UPDATE);
	}
#endif

	nscd_flush_cache ("passwd");
	nscd_flush_cache ("group");
	sssd_flush_cache (SSSD_DB_PASSWD | SSSD_DB_GROUP);

#ifdef WITH_SELINUX
	if (Zflg) {
		if ('\0' != *user_selinux) {
			if (set_seuser (user_name, user_selinux, user_selinux_range) != 0) {
				fprintf (stderr,
				         _("%s: warning: the user name %s to %s SELinux user mapping failed.\n"),
				         Prog, user_name, user_selinux);
#ifdef WITH_AUDIT
				audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
				              "modifying User mapping ",
				              user_name, user_id,
				              SHADOW_AUDIT_FAILURE);
#endif				/* WITH_AUDIT */
				fail_exit (E_SE_UPDATE);
			}
		} else {
			if (del_seuser (user_name) != 0) {
				fprintf (stderr,
				         _("%s: warning: the user name %s to SELinux user mapping removal failed.\n"),
				         Prog, user_name);
#ifdef WITH_AUDIT
				audit_logger (AUDIT_ADD_USER, Prog,
				              "removing SELinux user mapping",
				              user_name, user_id,
				              SHADOW_AUDIT_FAILURE);
#endif				/* WITH_AUDIT */
				fail_exit (E_SE_UPDATE);
			}
		}
	}
#endif				/* WITH_SELINUX */

	if (mflg) {
		move_home ();
	}

#ifndef NO_MOVE_MAILBOX
	if (lflg || uflg) {
		move_mailbox ();
	}
#endif				/* NO_MOVE_MAILBOX */

	if (uflg) {
#ifdef ENABLE_LASTLOG
		update_lastlog ();
#endif /* ENABLE_LASTLOG */
		update_faillog ();
	}

	if (!mflg && (uflg || gflg)) {
		struct stat sb;

		if (stat (dflg ? prefix_user_newhome : prefix_user_home, &sb) == 0 &&
			((uflg && sb.st_uid == user_newid) || sb.st_uid == user_id)) {
			/*
			 * Change the UID on all of the files owned by
			 * `user_id' to `user_newid' in the user's home
			 * directory.
			 *
			 * move_home() already takes care of changing the
			 * ownership.
			 *
			 */
#ifdef WITH_AUDIT
			if (uflg || gflg) {
				audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
					      "changing home directory owner",
					      user_newname, user_newid, 1);
			}
#endif
			if (chown_tree (dflg ? prefix_user_newhome : prefix_user_home,
			                user_id,
			                uflg ? user_newid  : (uid_t)-1,
			                user_gid,
			                gflg ? user_newgid : (gid_t)-1) != 0) {
				fprintf (stderr,
				         _("%s: Failed to change ownership of the home directory"),
				         Prog);
				fail_exit (E_HOMEDIR);
			}
		}
	}

	return E_SUCCESS;
}