This file is indexed.

/usr/lib/perl5/Cyrus/IMAP/Shell.pm is in kolab-libcyrus-imap-perl 2.2.13p1-0.3build1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# 
# Copyright (c) 2000 Carnegie Mellon University.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer. 
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#
# 3. The name "Carnegie Mellon University" must not be used to
#    endorse or promote products derived from this software without
#    prior written permission. For permission or any other legal
#    details, please contact  
#      Office of Technology Transfer
#      Carnegie Mellon University
#      5000 Forbes Avenue
#      Pittsburgh, PA  15213-3890
#      (412) 268-4387, fax: (412) 268-7395
#      tech-transfer@andrew.cmu.edu
#
# 4. Redistributions of any form whatsoever must retain the following
#    acknowledgment:
#    "This product includes software developed by Computing Services
#     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
#
# CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
# FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
# AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
# OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# $Id: Shell.pm,v 1.37 2006/03/23 15:41:56 jeaton Exp $
#
# A shell framework for Cyrus::IMAP::Admin
#
# run(*FH|'FH')
#	read commands from the filehandle and pass to exec(); defaults to
#	__DATA__
# shell
#	= run(*STDIN)
#
# This isn't derived from CPAN.pm, first because I need to support the stuff
# that makes it act at least somewhat like the old cyradm and second because
# I'm pretty sure this will have to be released under the crappy TTO license
# instead of the GPL/Artistic License.
#

package Cyrus::IMAP::Shell;
use strict;

use IO::File;
use Cyrus::IMAP::Admin;
use Getopt::Long;
use Exporter;
use POSIX ();
use Carp qw(confess);

use vars qw(@ISA @EXPORT $VERSION *cyradm);
$VERSION = "1.00";
@ISA = qw(Exporter);
@EXPORT = qw(cyradm shell run);

# note aliases
my %builtins = (exit =>
		  [\&_sc_exit, '[number]', 'exit cyradm'],
		quit => 'exit',
		help =>
		  [\&_sc_help, '[command]', 'show commands'],
		'?' => 'help',
		lam => 'listacl',
		listacl =>
		  [\&_sc_listacl, 'mailbox', 'list ACLs on mailbox'],
		listaclmailbox => 'listacl',
		lm => 'listmailbox',
		listmailbox =>
		  [\&_sc_list, '[-subscribed] [pattern [base]]',
		   'list mailboxes'],
		server =>
		  [\&_sc_server, '[-noauthenticate] [server]',
		   'show current server or connect to server'],
		servername => 'server',
		connect => 'server',
		authenticate =>
		  [\&_sc_auth,
		   '[-minssf N] [-maxssf N] [-mechanisms list] [user]',
		   'authenticate to server'],
		auth => 'authenticate',
		login => 'authenticate',
		listquota =>
		  [\&_sc_quota, 'root', 'list quotas on specified root'],
		lq => 'listquota',
		listquotaroot =>
		  [\&_sc_quotaroot, 'mailbox',
		   'show quota roots and quotas for mailbox'],
		lqr => 'listquotaroot',
		lqm => 'listquotaroot',
		disconnect =>
		  [\&_sc_disconn, '', 'disconnect from current server'],
		disc => 'disconnect',
		chdir =>
		  [\&_sc_chdir, 'directory', 'change current directory'],
		cd => 'chdir',
		createmailbox =>
		  [\&_sc_create, '[--partition partition] mailbox [partition]',
		   'create mailbox'],
		create => 'createmailbox',
		cm => 'createmailbox',
		deleteaclmailbox =>
		  [\&_sc_deleteacl, 'mailbox id [id ...]',
		   'remove ACLs from mailbox'],
		deleteacl => 'deleteaclmailbox',
		dam => 'deleteaclmailbox',
		deletemailbox =>
		  [\&_sc_delete, 'mailbox [host]', 'delete mailbox'],
		delete => 'deletemailbox',
		dm => 'deletemailbox',
		info =>
		  [\&_sc_info, '[mailbox]',
		   'display mailbox/server metadata'],
		mboxcfg =>
		  [\&_sc_mboxcfg, 'mailbox [comment|news2mail|expire|squat|/<explicit annotation>] value',
		   'configure mailbox'],
		mboxconfig => 'mboxcfg',
		reconstruct =>
		  [\&_sc_reconstruct, 'mailbox', 'reconstruct mailbox (if supported)'],
		renamemailbox =>
		  [\&_sc_rename,
		   '[--partition partition] oldname newname [partition]',
		   'rename (and optionally relocate) mailbox'],
		rename => 'renamemailbox',
		renm => 'renamemailbox',
		setaclmailbox =>
		  [\&_sc_setacl, 'mailbox id rights [id rights ...]',
		   'set ACLs on mailbox'],
		setacl => 'setaclmailbox',
		sam => 'setaclmailbox',
		setinfo =>
		  [\&_sc_setinfo, '[motd|comment|admin|shutdown|expire|squat] text',
		   'set server metadata'],
		setquota =>
		  [\&_sc_setquota,
		   'mailbox resource value [resource value ...]',
		   'set quota on mailbox or resource'],
		sq => 'setquota',
		version =>
		  [\&_sc_version, '',
		   'display version info of current server'],
		ver => 'version',
		xfermailbox =>
		  [\&_sc_xfer,
		   '[--partition partition] mailbox server [partition]',
		   'transfer (relocate) a mailbox to a different server'],
		xfer => 'xfermailbox',
		subscribe =>
		  [\&_sc_subscribe, '[mailbox]',
                  'subscribe to a mailbox'],
		sub => 'subscribe',
		unsubscribe =>
		  [\&_sc_unsubscribe, '[mailbox]',
                  'unsubscribe from a mailbox'],
		unsub => 'unsubscribe',
		#? alias
		#? unalias
		#? load
		#? unload
	       );

# ugh.  ugh.  suck.  aieee.
my $use_rl = 'Cyrus::IMAP::DummyReadline';
{
  if (eval { require Term::ReadLine; }) {
    $use_rl = 'Term::ReadLine';
  }
}

# callback when stream closes
sub _cb_eof {
  my %cb = @_;
  # indicate that the connection went away
  print STDERR "\nConnection to server lost.\n";
  ${$cb{-rock}} = undef;
}

# okay, this sucks.  the alternatives are worse.
my $coll_command = '';

# originally I used Text::ParseWords::shellwords; unfortunately, that is a
# bit inaccurate because it doesn't word-break at shell metacharacters.  which
# I need.  (also need to know when a metachar is a metachar on return.
sub _nexttoken {
  my $lr = shift;
  $$lr =~ s/^(\s+)// and $coll_command .= $1;
  my $quoted = 0;
  my $q = '';

  my @tok = ('', undef);
  # this is cute.  (shells are funny that way)
  # we parse "words" which are delimited by whitespace.  except that if a
  # quote appears, we have to gobble to the closing quote and then continue
  # with what we were doing.  and outside quotes, we need to look for special
  # characters (in this case, /&<>;/) and break "words" there.
  while ($$lr ne '' && ($quoted || $$lr !~ /^\s/)) {
    $tok[1] ||= 0;
    if ($q eq '' && $$lr =~ /^([&<>;])/) {
      last if $tok[0] ne '';
      $tok[0] = $1;
      $coll_command .= $1;
      $$lr =~ s///;
      $tok[1] = 1;
      last;
    }
    if ($$lr =~ /^([^&<>;\'\"\$\\\s]+)/) {
      $tok[0] .= $1;
      $coll_command .= $1;
      $$lr =~ s///;
      next;
    }
    if ($$lr =~ /^\\(.)/) {
      # gack.  "consistency?  wazzat?"
      $coll_command .= "\\" . $1;
      $tok[0] .= "'" if $q eq "'" && $1 ne "'";
      $tok[0] .= $1;
      $$lr =~ s///;
      next;
    }
    if ($$lr =~ /^\$(\{(\w+)\}|(\w+))/) {
      $coll_command .= "\$" . $1;
      # if someone asks for shell var qualifiers I will kill them
      $$lr =~ s//$ENV{$+}/;
      $$lr =~ s/^(\s+)// and $coll_command .= $1 if $q;
      redo;
    }
    if ($$lr =~ /^([\'\"])/ && $q eq 'x') {
      $q = '';
      $coll_command .= $1;
      $$lr =~ s///;
      $quoted = !$quoted;
      next;
    }
    if ($$lr =~ /^([\'\"])/ && $q eq '') {
      $q = 'x';
      $coll_command .= $1;
      $$lr =~ s///;
      $quoted = !$quoted;
      next;
    }
    $$lr =~ s/^(.)//;
    $tok[0] .= $1;
    $coll_command .= $1;
  }
  @tok;
}

# relatively trivial... except for the shell fallback.
sub _execvv {
  my ($cyrref, $cmd, $av0, $fa, $lfa, @argv) = @_;
  while (defined($builtins{$av0}) && !ref($builtins{$av0})) {
    $av0 = $builtins{$av0};
  }
  if (defined($builtins{$av0})) {
    &{$builtins{$av0}[0]}($cyrref, $av0, $fa, $lfa, @argv);
  }
  else {
    my $pid = fork;
    if (!defined($pid)) {
      die "fork: $!\n";
    }
    elsif ($pid) {
      waitpid($pid, 0);
    }
    else {
      $argv[0] =~ s!^.*/!!;
      my $fd = 0;
      # process redirections in $fa
      # sorted so lower $lfa->[$fh]->fileno consumed before $fh!
      foreach my $fh (sort {$a->fileno <=> $b->fileno} @$lfa) {
	if (!defined($fh)) {
	  POSIX::close($fd);
	} else {
	  POSIX::dup2($fh->fileno, $fd);
	}
	$fd++;
      }
      foreach my $fh (@$lfa) {
	POSIX::close($fd) if defined($fh) && $fh->fileno > $fd;
      }
      # anything else left open is just lost.  sorry.
      exec $cmd;
      die "$av0: $!\n";
    }
  }
}

# wrapper to trap errors and report them.
# (there are two such, one for "program" errors and one for "shell" errors...)
sub _execv {
  my ($cyrref, $cmd, $av0, $fa, $lfa, @argv) = @_;
  my $rc;
  local($@);
  if (!defined(eval { $rc = &_execvv; })) {
    $lfa->[2]->print($@);
    $lfa->[2]->print("\n") unless substr($@, -1, 1) eq "\n";
    $rc = -1;
  }
}

# ick
sub _redir {
  my ($fha, $op, $dst, $src) = @_;
  my ($rop, $amp);
  if ($op =~ s/\&$//) {
    $amp = '&';
  } else {
    $amp = '';
  }
  if ($op eq '>') {
    $rop = O_WRONLY|O_CREAT|O_TRUNC;
    $src = 1 if !defined($src) || $src eq '';
  }
  elsif ($op eq '>>') {
    $rop = O_WRONLY|O_CREAT|O_APPEND;
    $src = 1 if !defined($src) || $src eq '';
  }
  elsif ($op eq '<') {
    $rop = O_RDONLY;
    $src = 0 if !defined($src) || $src eq '';
  }
  else {
    die "can't handle \`$op' redirection\n";
  }
  if ($amp) {
    die "invalid file descriptor \`$dst'\n" if $dst ne '-' && $dst != /^\d+$/;
    if ($dst eq '-') {
      $fha->[$src] = undef;
    }
    elsif (!defined($fha->[$dst])) {
      die "file descriptor \`$dst' not open\n";
    }
    else {
      $fha->[$src] = IO::File->new("$op&" . $fha->[$dst]->fileno);
    }
  } else {
    $fha->[$src] = IO::File->new($dst, $rop) or die "$dst: $!\n";
  }
}

# this was once trivial, then I added parsing for redirection...
sub _exec {
  my ($cyrref, $fa, $cmd) = @_;
  $fa ||= [*STDIN, *STDOUT, *STDERR];
  # clone it:  only "exec" has permanent effects on the fh stack
  my $lfa = [@$fa];
  my @argv = ();
  my $state = '';
  my ($tok, $type);
  while (($tok, $type) = _nexttoken(\$cmd) and defined($type)) {
    if (!$type) {
      if ($state eq '') {
	# @@ here is where we should do aliasing, if we do it at all
	push(@argv, $tok);
      }
      else {
	# at this point, $state is the redirection (/^([<>])\1?\&?$/) and
	# $arg->[0] is the destination.  if $argv[$#argv] matches /^\d+$/,
	# it is the affected file handle.
	my $target;
	$target = pop(@argv) if $argv[-1] =~ /^\d+$/;
	_redir($lfa, $state, $tok, $target);
	$state = '';
      }
    }
    elsif ($tok eq ';') {
      _execv($cyrref, $coll_command, $argv[0], $fa, $lfa, @argv);
      $coll_command = '';
      @argv = ();
    }
    elsif ($tok eq '&') {
      if ($state ne '<' && $state ne '>') {
	die "syntax error: cannot deal with \`&' here\n";
      }
      $state .= '&';
    }
    elsif ($tok eq '<' || $tok eq '>') {
      if ($state ne '' && ($state ne $tok || $state eq '<')) {
	die "syntax error: cannot deal with \`$tok' here\n";
      }
      $state .= $tok;
    }
    else {
      die "syntax error: don't understand \`$tok'\n";
    }
  }
  if (@argv) {
    _execv($cyrref, $coll_command, $argv[0], $fa, $lfa, @argv);
    $coll_command = '';
  }
}

# not too horrible
sub _run {
  my $cyradm = shift;
  my $fstk = shift || [*STDIN, *STDOUT, *STDERR];
  my $fin = shift || $fstk->[0] || *STDIN;
  my ($hfh, $line);
  $hfh = $use_rl->new('cyradm shell', $fin, $fstk->[1]);
  $hfh->ornaments(0);
  my $rc;
  while (defined ($line = $hfh->readline((defined $$cyradm ?
					  $$cyradm->servername :
					  'cyradm') . '> '))) {
    local($@);
    if (!defined(eval { $rc = _exec($cyradm, $fstk, $line); })) {
      $fstk->[2]->print($@);
      $fstk->[2]->print("\n") unless substr($@, -1, 1) eq "\n";
      $rc = -1;
    }
  }
  $rc;
}

# trivial; wrapper for _run with correct setup
sub run {
  my $cyradm;
  _run(\$cyradm, [*STDIN, *STDOUT, *STDERR], *__DATA__);
}

# All the real work is done by _run(); this is a convenience wrapper.
# (It's not as trivial as run() because it does things expected of standalone
# programs, as opposed to things expected from within a program.)
sub shell {
  my ($server, $port, $authz, $auth, $systemrc, $userrc, $dorc, $mech, $pw) =
    ('', 143, undef, $ENV{USER} || $ENV{LOGNAME}, '/etc/cyradmrc.pl',
     "$ENV{HOME}/.cyradmrc.pl", 1, undef, undef);
  GetOptions('user|u=s' => \$auth,
	     'authz|z=s' => \$authz,
	     'rc|r!' => \$dorc,
	     'systemrc|S=s' => \$systemrc,
	     'userrc=s' => \$userrc,
	     'server|s=s' => \$server,
	     'port|p=i' => \$port,
	     'auth|a=s' => \$mech,
	     'password|w=s' => \$pw,
	     'help|h' => sub { cyradm_usage(); exit(0); }
	    );
  if ($server ne '' && @ARGV) {
    die "cyradm: may not specify server both with --server and bare arg\n";
  }
  if (@ARGV) {
    $server = shift(@ARGV);
    $port = shift(@ARGV) if @ARGV;
    cyradm_usage() if @ARGV;
  }
  my $cyradm;
  if ($server ne '') {
    $cyradm = Cyrus::IMAP::Admin->new($server, $port)
      or die "cyradm: cannot connect to server\n";
    $cyradm->addcallback({-trigger => 'EOF',
			  -callback => \&_cb_eof,
			  -rock => \$cyradm});
    $cyradm->authenticate(-authz => $authz, -user => $auth,
			  -mechanism => $mech, -password => $pw)
      or die "cyradm: cannot authenticate to server" . (defined($mech)?" with $mech":"") . " as $auth\n";
  }
  my $fstk = [*STDIN, *STDOUT, *STDERR];
  if ($dorc && $systemrc ne '' && -f $systemrc) {
    my $fh = IO::File->new($systemrc, O_RDONLY);
    _run(\$cyradm, $fstk, *$fh) if $fh;
  }
  if ($dorc && $userrc ne '' && -f $userrc) {
    my $fh = IO::File->new($userrc, O_RDONLY);
    _run(\$cyradm, $fstk, *$fh) if $fh;
  }
  _run(\$cyradm, $fstk, *STDIN);
}
*cyradm = \&shell;

###############################################################################

# show cyradm command line arguments
sub cyradm_usage {
  print <<'END_OF_HELP';
Usage: cyradm [args] server
  --user <user>         Connect as <user> (authentication name)
  --authz <user>        Authorize as <user>
  --[no]rc              (Do not) load the configuration files
  --systemrc <file>     Use system-wide configuration <file>
  --userrc <file>       Use user configuration <file>
  --port <port>         Connect to server on <port>
  --auth <mechanism>    Authenticate with <mechanism>

Defaults to interactive mode. Please see man cyradm(1) and the 'help' command
in the cyradm-shell for details.
END_OF_HELP
}

# help display
sub do_help {
  my ($fd, $cmd, @list) = @_;
  if (!@list || grep($_ eq $cmd, @list)) {
    unless (defined($builtins{$cmd})) {
      $fd->print("unknown command: $cmd\n");
      return 0;
    }
    if (!ref($builtins{$cmd})) {
      $fd->print("$cmd, alias for ");
      do_help($fd, $builtins{$cmd}, $builtins{$cmd}, @list);
    } else {
      $fd->print("$cmd $builtins{$cmd}[1]\n\t$builtins{$cmd}[2]\n");
    }
  }
  1;
}

sub _sc_help {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt, $rc);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: help [command]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  $rc = 0;
  if (@nargv) {
    foreach my $cmd (sort {$a cmp $b} @nargv) {
      $rc = 1 if !do_help($lfh->[1], $cmd, @nargv);
    }
  } else {
    # compress commands and their aliases, plus one line of help
    my %cmds;
    my $cmd;
    foreach $cmd (keys %builtins) {
      if (ref($builtins{$cmd})) {
	$cmds{$cmd} ||= [[], ''];
	$cmds{$cmd}[1] = $builtins{$cmd}[2];
      } else {
	$cmds{$builtins{$cmd}} ||= [[], ''];
	push(@{$cmds{$builtins{$cmd}}[0]}, $cmd);
      }
    }
    my $nwid = 0;
    foreach $cmd (keys %cmds) {
      $cmds{$cmd}[0] = join(', ', $cmd, @{$cmds{$cmd}[0]});
      $nwid = length($cmds{$cmd}[0]) if $nwid < length($cmds{$cmd}[0]);
    }
    foreach $cmd (sort {$a cmp $b} keys %cmds) {
      $lfh->[1]->printf("%-*s  %s\n", $nwid, $cmds{$cmd}[0], $cmds{$cmd}[1]);
    }
  }
  $rc;
}

sub _sc_exit {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: exit [number]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv > 1) {
    die "usage: exit [number]\n";
  }
  push(@nargv, 0) if !@nargv;
  exit $nargv[0];
}

sub _sc_list {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my $cmd = 'listmailbox';
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt ne '' && '-subscribed' =~ /^\Q$opt/ || $opt eq '--subscribed') {
      $cmd = 'listsubscribed';
    }
    elsif ($opt =~ /^-/) {
      die "usage: listmailbox [-subscribed] [pattern [base]]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv > 2) {
    die "usage: listmailbox [-subscribed] [pattern [base]]\n";
  }
  push(@nargv, '*') if !@nargv;
  if (!$cyrref || !$$cyrref) {
    die "listmailbox: no connection to server\n";
  }
  my ($l, $w, @l);
  my @res = $$cyrref->$cmd(@nargv);
  if (defined $$cyrref->error) {
    $lfh->[2]->print($$cyrref->error, "\n");
    return 1;
  }
  foreach my $mbx (@res) {
    $l = $mbx->[0];
    if ($mbx->[1] ne '') {
      $l .= ' (' . $mbx->[1] . ')';
    }
    if (length($l) + 1 > $w) {
      $w = length($l) + 1;
    }
    push(@l, $l);
  }
  return 1 if !@l;
  @l = sort {$a cmp $b} @l;
  my $ll = $ENV{COLUMNS} || 79;
  $w = $ll if $w > $ll;
  my $n = int($ll / $w);
  my $c;
  for ($l = 0; $l < int((@l + $n - 1) / $n); $l++) {
    for ($c = 0; $c < @l; $c += int((@l + $n - 1) / $n)) {
      if ($l + $c < @l) {
	$lfh->[1]->print($l[$l + $c], ' ' x ($w + 1 - length($l[$l + $c])));
      }
    }
    $lfh->[1]->print("\n");
  }
  0;
}

sub _sc_listacl {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: listaclmailbox mailbox\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv != 1) {
    die "usage: listaclmailbox mailbox\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "listaclmailbox: no connection to server\n";
  }

  sub showacl($@) {
    my $spaces = shift;
    my @nargv = shift;
    my %acl = $$cyrref->listaclmailbox(@nargv);
    if (defined $$cyrref->error) {
      $lfh->[2]->print($$cyrref->error, "\n");
      return 1;
    }
    foreach my $acl (keys %acl) {
      for(my $i = 0; $i < $spaces; $i++) {
	$lfh->[1]->print(" ");
      }
      $lfh->[1]->print($acl, " ", $acl{$acl}, "\n");
    }
    return 0;
  }
  
  if($nargv[0] =~ /(\*|%)/) {
    # list operation
    my @res = $$cyrref->listmailbox(($nargv[0]));
    foreach my $mbx (@res) {
      my $name = $mbx->[0];
      my $flags = $mbx->[1];
      next if($flags =~ /(\\noselect|\\nonexistent|\\placeholder)/i);
      $lfh->[1]->print($name,":\n");
      $nargv[0] = $name;
      if(showacl(2,@nargv) != 0) {
	return 1;
      }
    }
  } else {
    return showacl(0,@nargv);
  }
  return 0;
}

sub _sc_server {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt, $auth);
  shift(@argv);
  $auth = 1;
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt ne '' && '-noauthenticate' =~ /^\Q$opt/ ||
	$opt eq '--noauthenticate') {
      $auth = 0;
      next;
    }
    if ($opt =~ /^-/) {
      die "usage: server [-noauthenticate] [server]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (!@nargv) {
    if (!$cyrref || !$$cyrref) {
      die "server: no connection to server\n";
    }
    $lfh->[1]->print($$cyrref->servername, "\n");
    0;
  }
  elsif (@nargv == 1) {
    $$cyrref = Cyrus::IMAP::Admin->new($nargv[0])
      or die "server: $nargv[0]: cannot connect to server\n";
    if ($auth) {
      $$cyrref->authenticate or die "server: $nargv[0]: cannot authenticate\n";
    }
    0;
  }
  else {
    die "usage: server [-noauthenticate] [server]\n";
  }
}

sub _sc_auth {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt, %opts, $want);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    if (defined $want) {
      $opts{$want} = $opt;
      $want = undef;
      next;
    }
    last if $opt eq '--';
    if ($opt ne '' && '-mechanisms' =~ /^\Q$opt/ || $opt eq '--mechanisms') {
      $want = '-mechanism';
      next;
    }
    if ($opt ne '' && '-minssf' =~ /^\Q$opt/ || $opt eq '--minssf') {
      $want = '-minssf';
      next;
    }
    if ($opt ne '' && '-maxssf' =~ /^\Q$opt/ || $opt eq '--maxssf') {
      $want = '-maxssf';
      next;
    }
    if ($opt ne '' && '-service' =~ /^\Q$opt/ || $opt eq '--service') {
      $want = '-service';
      next;
    }
    if ($opt =~ /^-/) {
      die "usage: authenticate [-minssf N] [-maxssf N] [-mechanisms STR]\n".
	  "                    [-service name] [user]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv > 1) {
    die "usage: authenticate [-minssf N] [-maxssf N] [-mechanisms STR]\n".
        "                    [-service name] [user]\n";
  }
  if (@nargv) {
    $opts{-user} = shift(@nargv);
  }
  if (!$cyrref || !$$cyrref) {
    die "authenticate: no connection to server\n";
  }
  unless ($$cyrref->authenticate(%opts)) {
    my $sn = $$cyrref->servername;
    die "authenticate: authentication to server $sn failed\n";
  } 
  0;
}

sub _sc_quota {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: listquota root\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv != 1) {
    die "usage: listquota root\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "listquota: no connection to server\n";
  }
  my %quota = $$cyrref->listquota(@nargv);
  foreach my $quota (keys %quota) {
    $lfh->[1]->print(" ", $quota, " ", $quota{$quota}[0], "/",
		     $quota{$quota}[1]);
    if ($quota{$quota}[1]) {
      $lfh->[1]->print(" (", $quota{$quota}[0] * 100 / $quota{$quota}[1], "%)");
    }
  }
  $lfh->[1]->print("\n");
  0;
}

sub _sc_quotaroot {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: listquotaroot mailbox\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv != 1) {
    die "usage: listquotaroot mailbox\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "listquotaroot: no connection to server\n";
  }
  my ($root, %quota) = $$cyrref->listquotaroot(@nargv);
  $lfh->[1]->print($root);
  my ($used, $tot);
  foreach my $quota (keys %quota) {
    ($used, $tot) = split(/ /, $quota{$quota});
    $lfh->[1]->print(" ", $quota, " ", $quota{$quota}[0], "/",
		     $quota{$quota}[1]);
    if ($quota{$quota}[1]) {
      $lfh->[1]->print(" (", $quota{$quota}[0] * 100 / $quota{$quota}[1], "%)");
    }
  }
  $lfh->[1]->print("\n");
  0;
}

sub _sc_disconn {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: disconnect\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv != 0) {
    die "usage: disconnect\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "disconnect: no connection to server\n";
  }
  $$cyrref = undef;
  0;
}

sub _sc_chdir {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: chdir directory\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv != 1) {
    die "usage: chdir directory\n";
  }
  chdir($nargv[0]) or die "chdir: $nargv[0]: $!\n";
  0;
}

sub _sc_create {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt, $part, $want);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    if ($want) {
      $part = $opt;
      $want = undef;
      next;
    }
    if ($opt ne '' && '-partition' =~ /^\Q$opt/ || $opt eq '--partition') {
      $want = 1;
      next;
    }
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: createmailbox [--partition partition] mailbox [partition]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (!@nargv || @nargv > 2) {
    die "usage: createmailbox [--partition partition] mailbox [partition]\n";
  }
  if (defined($part)) {
      push(@nargv, $part)
  }
  if (!$cyrref || !$$cyrref) {
    die "createmailbox: no connection to server\n";
  }
  $$cyrref->create(@nargv) || die "createmailbox: " . $$cyrref->error . "\n";
  0;
}

sub _sc_delete {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: deletemailbox mailbox [host]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (!@nargv || @nargv > 2) {
    die "usage: deletemailbox mailbox [host]\n";
  }
  # @@ do I really care?
  if (@nargv == 2) {
    die "deletemailbox: host argument only supported in IMSP\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "deletemailbox: no connection to server\n";
  }

  if($nargv[0] =~ /(\*|%)/) {
    # list operation
    my @res = $$cyrref->listmailbox(($nargv[0]));
    foreach my $mbx (@res) {
      my $name = $mbx->[0];
      my $flags = $mbx->[1];
      next if($flags =~ /(\\noselect|\\nonexistent|\\placeholder)/i);
      print "Deleting mailbox $name...";
      $nargv[0] = $name;
      my $rc = $$cyrref->delete(@nargv);
      if(!defined($rc)) {
	print $$cyrref->error . "\n";
	last;
      } else {
	print "OK.\n";
      }
    }
  } else {
    $$cyrref->delete(@nargv) || die "deletemailbox: " . $$cyrref->error . "\n";
  }
  0;
}

sub _sc_reconstruct {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  my $recurse = 0;
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      if($opt eq "-r") {
	$recurse = 1;
      } else {
	die "usage: reconstruct [-r] mailbox\n";
      }
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (!@nargv || @nargv > 1) {
    die "usage: reconstruct [-r] mailbox\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "reconstruct: no connection to server\n";
  }
  $$cyrref->reconstruct(@nargv) || die "reconstruct: " .$$cyrref->error. "\n";
  0;
}

sub _sc_rename {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt, $want, $part);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    if ($want) {
      $part = $opt;
      $want = undef;
      next;
    }
    if ($opt ne '' && '-partition' =~ /^\Q$opt/ || $opt eq '--partition') {
      $want = 1;
      next;
    }
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: renamemailbox [--partition name] oldname " .
	  "newname [partition]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  $part = pop(@nargv) if @nargv > 2 && !defined($part);
  if (@nargv != 2) {
    die "usage: renamemailbox [--partition name] oldname " .
	"newname [partition]\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "renamemailbox: no connection to server\n";
  }
  $$cyrref->rename($nargv[0], $nargv[1], $part) ||
    die "renamemailbox: " . $$cyrref->error . "\n";
  0;
}

sub _sc_xfer {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt, $want, $part);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    if ($want) {
      $part = $opt;
      $want = undef;
      next;
    }
    if ($opt ne '' && '-partition' =~ /^\Q$opt/ || $opt eq '--partition') {
      $want = 1;
      next;
    }
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: xfermailbox [--partition name] mailbox " .
	  "server [partition]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  $part = pop(@nargv) if @nargv > 2 && !defined($part);
  if (@nargv != 2) {
    die "usage: xfermailbox [--partition name] mailbox " .
	"server [partition]\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "xfermailbox: no connection to server\n";
  }
  $$cyrref->xfer($nargv[0], $nargv[1], $part) ||
    die "xfermailbox: " . $$cyrref->error . "\n";
  0;
}

sub _sc_deleteacl {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: deleteaclmailbox mailbox id [id ...]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv < 2) {
    die "usage: deleteaclmailbox mailbox id [id ...]\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "deleteaclmailbox: no connection to server\n";
  }

  if($nargv[0] =~ /(\*|%)/) {
    # list operation
    my @res = $$cyrref->listmailbox(($nargv[0]));
    foreach my $mbx (@res) {
      my $name = $mbx->[0];
      my $flags = $mbx->[1];
      next if($flags =~ /(\\noselect|\\nonexistent|\\placeholder)/i);
      print "Deleting acl on $name...";
      $nargv[0] = $name;
      my $rc = $$cyrref->deleteacl(@nargv);
      if(!defined($rc)) {
	print $$cyrref->error . "\n";
	last;
      } else {
	print "OK.\n";
      }
    }
  } else {
    $$cyrref->deleteacl(@nargv) ||
      die "deleteaclmailbox: " . $$cyrref->error . "\n";
  }

  0;
}

sub _sc_setacl {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: setaclmailbox mailbox id rights [id rights ...]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv < 3 || (@nargv - 1) % 2) {
    die "usage: setaclmailbox mailbox id rights [id rights ...]\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "setaclmailbox: no connection to server\n";
  }

  if($nargv[0] =~ /(\*|%)/) {
    # list operation
    my @res = $$cyrref->listmailbox(($nargv[0]));
    foreach my $mbx (@res) {
      my $name = $mbx->[0];
      my $flags = $mbx->[1];
      next if($flags =~ /(\\noselect|\\nonexistent|\\placeholder)/i);
      print "Setting ACL on $name...";
      $nargv[0] = $name;
      my $rc = $$cyrref->setacl(@nargv);
      if(!defined($rc)) {
	print $$cyrref->error . "\n";
	last;
      } else {
	print "OK.\n";
      }
    }
  } else {
    $$cyrref->setacl(@nargv) || die "setaclmailbox: " . $$cyrref->error . "\n";
  }
  0;
}

sub _sc_setquota {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die ("usage: setquota mailbox limit num [limit num ...]\n" .
	   "       setquota mailbox num\n");
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv == 2) {
      my ($mbox, $limit) = @nargv;
      if ($limit eq 'none') {
	  @nargv = ($mbox);
	  print "remove quota\n";
      } else {
	  @nargv = ($mbox, "STORAGE", $limit);
	  print "quota:", $limit, "\n";
      }
  }
  if ((@nargv - 1) % 2) {
    die ("usage: setquota mailbox limit num [limit num ...]\n" .
	 "       setquota mailbox num\n");
  }
  if (!$cyrref || !$$cyrref) {
    die "setquota: no connection to server\n";
  }
  $$cyrref->setquota(@nargv) || die "setquota: " . $$cyrref->error . "\n";
  0;
}

sub _sc_version {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: version\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv != 0) {
    die "usage: version\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "version: no connection to server\n";
  }

  my $info;
  $$cyrref->addcallback({-trigger => 'ID',
		      -callback => sub {
			my %d = @_;
			$info = $d{-text};
		      }});
  my ($rc, $msg) = $$cyrref->send('', '', 'ID NIL');
  $$cyrref->addcallback({-trigger => 'ID'});
  if ($rc ne 'OK') {
    $lfh->[2]->print($msg, "\n");
    return 1;
  }

  if ($info eq 'NIL') {
    $lfh->[1]->print("no version info returned by server\n");
    return 0;
  }
  while ($info =~ s/\"([^\"]+)\"\s+(\"[^\"]+\"|NIL)\s*//) {
    my $field = $1;
    my $value = $2;
    $value =~ s/\"//g;			# strip quotes
    # split environment into multiple lines
    $value =~ s/;/\n            /g if $field eq 'environment';
    $value = '' if $value eq 'NIL';	# convert NIL to empty string
    $lfh->[1]->printf("%-11s: %s\n", $field, $value);
  }
  0;
}

sub _sc_info {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: info [mailbox]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (!$cyrref || !$$cyrref) {
    die "info: no connection to server\n";
  }
  my %info = $$cyrref->getinfo(@nargv);
  if (defined $$cyrref->error) {
    $lfh->[2]->print($$cyrref->error, "\n");
    return 1;
  }

  # keep track of what mailboxes we've printed a header for already
  my %section = ();
  foreach my $attrib (sort keys %info) {
    $attrib =~ /(\{.*\})/;
    my $sect = $1;
    if(!defined($sect)) {
	$sect = "Server Wide";
    }

    if(!exists $section{$sect}) {
	$section{$sect} = 'x';
	print "$sect:\n";
    }

    $attrib =~ /([^\/]*)$/;
    my $attrname = $1;

    $lfh->[1]->print("  ", $attrname, ": ", $info{$attrib}, "\n");
  }
  0;
}

sub _sc_subscribe {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: subscribe [mailbox]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (!$cyrref || !$$cyrref) {
    die "subscribe: no connection to server\n";
  }
  $$cyrref->subscribe(@nargv);
  if (defined $$cyrref->error) {
    $lfh->[2]->print($$cyrref->error, "\n");
    return 1;
  }
  0;
}
sub _sc_unsubscribe {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    # gack.  bloody tcl.
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: unsubscribe [mailbox]\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (!$cyrref || !$$cyrref) {
    die "unsubscribe: no connection to server\n";
  }
  $$cyrref->unsubscribe(@nargv);
  if (defined $$cyrref->error) {
    $lfh->[2]->print($$cyrref->error, "\n");
    return 1;
  }
  0;
}

sub _sc_mboxcfg {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: mboxconfig mailbox [comment|news2mail|expire|squat|/<explicit annotation>] value\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv < 2) {
    die "usage: mboxconfig mailbox [comment|news2mail|expire|squat|/<explicit annotation>] value\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "mboxconfig: no connection to server\n";
  }
  $$cyrref->mboxconfig(@nargv) || die "mboxconfig: " . $$cyrref->error . "\n";
  0;
}

sub _sc_setinfo {
  my ($cyrref, $name, $fh, $lfh, @argv) = @_;
  my (@nargv, $opt);
  shift(@argv);
  while (defined ($opt = shift(@argv))) {
    last if $opt eq '--';
    if ($opt =~ /^-/) {
      die "usage: setinfo [motd|comment|admin|shutdown|expire|squat] text\n";
    }
    else {
      push(@nargv, $opt);
      last;
    }
  }
  push(@nargv, @argv);
  if (@nargv < 2) {
    die "usage: setinfo [motd|comment|admin|shutdown|expire|squat] text\n";
  }
  if (!$cyrref || !$$cyrref) {
    die "setinfo: no connection to server\n";
  }
  $$cyrref->setinfoserver(@nargv) || die "setinfo: " . $$cyrref->error . "\n";
  0;
}

###############################################################################

#
# This exists so I don't have to use a separate interface to read from a file.
#

package Cyrus::IMAP::DummyReadline;
use IO::File;

sub new {
  my ($class, $dummy, $in, $out) = @_;
  autoflush $out 1;
  bless {in => $in, out => $out}, $class;
}

sub ornaments {
  return;
}

sub readline {
  my ($self, $prompt) = @_;
  my $l;
  my $fh = $self->{in};
  my $ofh = $self->{out};
  print $ofh $prompt;
  return undef unless defined($l = <$fh>);
  chomp($l);
  $l;
}

1;

=head1 NAME

Cyrus::IMAP::Shell - Perl version of cyradm

=head1 SYNOPSIS

  $ cyradm [--user authid] [--authz authzid] [--[no]rc] [--systemrc file] [--userrc file] \
  > [--port n] [--auth mechanism] [--server] server

but possibly

  $ perl -MCyrus::IMAP::Shell -e 'run("myscript")'

or even (not recommended)

  use Cyrus::IMAP::Admin::Shell;

  run('myscriptname');

=head1 DESCRIPTION

This module implements B<cyradm> in Perl.  It is a shell around
L<Cyrus::IMAP::Admin>.  Commands are provided in both Tcl-compatible
forms and GNU-style long option forms.

=head1 COMMANDS

=over 4

=item C<authenticate> [C<--minssf> I<N>] [C<--maxssf> I<N>] [C<--mechanisms> I<list>] [I<user>]

=item C<auth> [C<--minssf> I<N>] [C<--maxssf> I<N>] [C<--mechanisms> I<list>] [I<user>]

=item C<login> [C<--minssf> I<N>] [C<--maxssf> I<N>] [C<--mechanisms> I<list>] [I<user>]

Authenticate to server.  You must already be connected to a server and
Cyrus imapd will refuse to allow you to re-authenticate once you have
authenticated once.

=item C<chdir> I<directory>

=item C<cd> I<directory>

Change directory.  A C<pwd> builtin is not provided, but the default command
action will run C<pwd> from a shell if invoked.

=item C<createmailbox> [C<--partition> I<partition>] I<mailbox>

=item C<createmailbox> I<mailbox> I<partition>

=item C<create> [C<--partition> I<partition>] I<mailbox>

=item C<create> I<mailbox> I<partition>

=item C<cm> [C<--partition> I<partition>] I<mailbox>

=item C<cm> I<mailbox> I<partition>

Create a mailbox on the default or a specified partition.  Both old-style
and getopt-style usages are accepted (combining them will produce an error).

=item C<deleteaclmailbox> I<mailbox> I<id> [...]

=item C<deleteacl> I<mailbox> I<id> [...]

=item C<dam> I<mailbox> I<id> [...]

Remove ACLs from the specified mailbox.

=item C<deletemailbox> I<mailbox>

=item C<delete> I<mailbox>

=item C<dm> I<mailbox>

Delete the specified mailbox.

Administrators do not have implicit delete rights on mailboxes.  Use the
B<setaclmailbox> command to grant the C<c> permission (or other permission
as specified by the deleteright configuration option in imapd.conf)
to your principal if you need to delete a mailbox you do not own. 

Note that the online help admits to an optional host argument.  This argument
is not currently used, and will be rejected with an error if specified; it
is reserved for IMSP.

=item C<disconnect>

=item C<disc>

Disconnect from the current server.  The prompt will revert to C<cyradmE<gt>>.

=item C<exit> [I<number>]

=item C<quit> [I<number>]

Exit B<cyradm>, optionally with a specific exit status; the exit status of the
last command will be used if one is not specified.

=item help [command]

=item ? [command]

Show help for C<command> or all commands.

=item C<info> [I<mailbox>]

Display the mailbox/server metadata.

=item listaclmailbox I<mailbox>

=item listacl I<mailbox>

=item lam I<mailbox>

List ACLs on the specified mailbox.

=item C<listmailbox> [C<--subscribed>] [I<pattern> [I<reference>]]

=item C<list> [C<--subscribed>] [I<pattern> [I<reference>]]

=item C<lm> [C<--subscribed>] [I<pattern> [I<reference>]]

List all, or all subscribed, mailboxes matching the specified pattern.
The pattern may have embedded wildcards C<'*'> or C<'%'>, which match
anything or anything except the separator character, respectively.

Mailboxes returned will be relative to the specified reference if one
is specified.  This allows a mailbox list to be limited to a particular
hierarchy.

In some cases when the C<'%'> wildcard is used to end a pattern, it may
match an entry which is not a mailbox but which contains other mailboxes.
In this case, the entry will be parenthesized to indicate that it is a
root for other mailboxes, as opposed to a mailbox itself.

=item C<listquota> I<root>

=item C<lq> I<root>

List quotas on specified root.  If the specified mailbox path does not have
a quota assigned, an error will be raised; see L<listquotaroot> for a way to
find the quota root for a mailbox.

=item C<listquotaroot> I<mailbox>

=item C<lqm> I<mailbox>

=item C<lqr> I<mailbox?>

show quota roots and quotas for mailbox

=item C<mboxconfig> I<mailbox> I<attribute> I<value>

=item C<mboxcfg> I<mailbox> I<attribute> I<value>

Set mailbox metadata.  A value of "none" will remove the attribute.
The currently supported attributes are: 

=over 4

=item C<comment>

Sets a comment or description associated with the mailbox.

=item C<expire>

Sets the number of days after which messages will be expired from the mailbox.

=item C<sieve>

Indicates the name of the global sieve script that should be run when
a message is delivered to the shared mailbox (not used for personal
mailboxes).

=item C<squat>

Indicates that the mailbox should have a squat index created for it.

=item C<news2mail>

Sets an email address to which messages injected into the server via NNTP 
will be sent.

=back 

=item C<renamemailbox> [C<--partition> I<partition>] I<oldname> I<newname>

=item C<rename> [C<--partition> I<partition>] I<oldname> I<newname>

=item C<renm> [C<--partition> I<partition>] I<oldname> I<newname>

=item C<renamemailbox> I<oldname> I<newname> [I<partition>]

=item C<rename> I<oldname> I<newname> [I<partition>]

=item C<renm> I<oldname> I<newname> [I<partition>]

Rename the specified mailbox, optionally moving it to a different partition.
Both old-style and getopt-style usages are accepted; combining them will
produce an error.

=item server [--noauthenticate] [server]

=item connect [--noauthenticate] [server]

=item servername [--noauthenticate] [server]

With no arguments, show the current server.  With an argument, connect to that
server.  It will prompt for automatic login unless the C<--noauthenticate>
option is specified.  (This may change; in particular, either automatic
authentication will be removed or all C<authenticate> options will be added.)

When connected to a server, B<cyradm>'s prompt changes from C<cyradmE<gt>> to
C<servernameE<gt>>, where I<servername> is the fully qualified domain name
of the connected server.

=item C<setaclmailbox> I<mailbox> I<id> I<rights> [I<id> I<rights> ...]

=item C<setacl> I<mailbox> I<id> I<rights> [I<id> I<rights> ...]

=item C<sam> I<mailbox> I<id> I<rights> [I<id> I<rights> ...]

Set ACLs on a mailbox.  The ACL may be one of the special strings C<none>,
C<read> (C<lrs>), C<post> (C<lrsp>), C<append> (C<lrsip>), C<write>
(C<lrswipcd>), or C<all> (C<lrswipcda>), or any combinations of the ACL codes:

=over 4

=item l

Lookup (visible to LIST/LSUB/UNSEEN)

=item r

Read (SELECT, CHECK, FETCH, PARTIAL, SEARCH, COPY source)

=item s

Seen (STORE \SEEN)

=item w

Write flags other than \SEEN and \DELETED

=item i

Insert (APPEND, COPY destination)

=item p

Post (send mail to mailbox)

=item c

Create (subfolders)

=item d

Delete (STORE \DELETED, EXPUNGE)

=item a

Administer (SETACL)

=back

=item C<setinfo> I<attribute> I<value>

Set server metadata.  A value of "none" will remove the attribute.
The currently supported attributes are:

=over 4

=item C<motd>

Sets a "message of the day".  The message gets displayed as an ALERT after
authentication.

=item C<comment>

Sets a comment or description associated with the server.

=item C<admin>

Sets the administrator email address for the server.

=item C<shutdown>

Sets a shutdown message.  The message gets displayed as an ALERT and
all users are disconnected from the server (subsequent logins are disallowed).

=item C<expire>

Sets the number of days after which messages will be expired from the
server (unless overridden by a mailbox annotation).

=item C<squat>

Indicates that all mailboxes should have a squat indexes created for
them (unless overridden by a mailbox annotation).

=back 

=item C<setquota> I<root> I<resource> I<value> [I<resource> I<value> ...]

=item C<sq> I<root> I<resource> I<value> [I<resource> I<value> ...]

Set a quota on the specified root, which may or may not be an actual mailbox.
The only I<resource> understood by B<Cyrus> is C<STORAGE>.  The units
are as defined in RFC 2087, groups of 1024 octets (i.e. Kilobytes).
The I<value> may be the special string C<none> which will remove the quota.

=item C<version>

=item C<ver>

Display the version info of the current server.

=item C<xfermailbox> [C<--partition> I<partition>] I<mailbox> I<server>

=item C<xfer> [C<--partition> I<partition>] I<mailbox> I<server>

=item C<xfermailbox> I<mailbox> I<server> [I<partition>]

=item C<xfer> I<mailbox> I<server> [I<partition>]

Transfer (relocate) the specified mailbox to a different server.
Both old-style and getopt-style usages are accepted; combining them will
produce an error.

=back

=head1 NOTES

GNU-style long options must be given in their entirety; Tcl-style options
may be abbreviated.

Tcl-style options are provided as a compatibility feature.  They will
probably go away in the future.

Multiple commands can be given on a line, separated by C<';'> characters.

All commands set an exit status, which at present is not useful.

Unknown commands are passed to a subshell for execution.

The Tcl version of B<cyradm> is used for scripting as well as interactively.
While this is possible to a limited extent by use of the C<run> method,
scripting would normally be done with C<Cyrus::IMAP::Admin>, which is far
more flexible than either interactive C<cyradm> or the Tcl scripting
mechanism for Cyrus.

B<cyradm> understands B</bin/sh>-style redirection:  any command can have
its standard or error output redirected, with all B<sh>-style redirections
(except C<E<lt>E<gt>>) supported.  It does not currently understand pipes
or backgrounding.

If the C<Term::Readline::Perl> or C<Term::Readline::GNU> modules are
available, B<cyradm> will use it.

An alias facility is implemented internally, but no access is currently
provided to it.  This will change, if only to allow some of the predefined
aliases to be removed if they conflict with useful shell commands.

=head1 AUTHOR

Brandon S. Allbery, allbery@ece.cmu.edu

=head1 SEE ALSO

Cyrus::IMAP::Admin
Term::ReadLine
sh(1), perl(1), imapd(8).

=cut