aboutsummaryrefslogtreecommitdiff
path: root/firma
blob: aa295db49e5fa2a86b988a9099a67c11322782f6 (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
#!/bin/bash
#
# firma: GnuPG-based encrypted mailing list manager
# Feedback: firma@sarava.org
#
#  Firma is free software; you can redistribute it and/or modify it under the
#  terms of the GNU General Public License as published by the Free Software
#  Foundation; either version 2 of the License, or (at your option) any later
#  version.
#
#  Firma is distributed in the hope that it will be useful, but WITHOUT ANY
#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
#  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along with
#  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
#  Place - Suite 330, Boston, MA 02111-1307, USA
#
# Usage:
#
# All firma parameters are passed through two different configuration files:
# firma.conf, containing general parameters needed to run the script, and a list
# specific file, containing its address, administrator(s), etc. In both files
# you should enter PARAMETER='value' (without spaces before or after the equal
# sign).
#
# firma.conf should contain the following parameters:
#
# GPG_BINARY= path to the GnuPG binary
# MAIL_AGENT= path to the mail transport agent to be used (e.g., sendmail)
# MAIL_AGENT_ARGS= command-line arguments to be passed to the command above
# LISTS_DIR= path to the mailing lists directory
#
# And it may contain the following optional parameters:
#
# USER= user that runs firma (usually the same as your MTA user);
#       defaults to "nobody"; you can also specify this parameter
#       in each mailing list config file if you plan to have one
#       user per mailing list
# GROUP= group that runs firma (usually the same as your MTA group);
#        defaults to "nobody"; you can also specify this parameter
#        in each mailing list config file if you plan to have one
#        group per mailing list
# LOG_TO_SYSLOG= set to "1" to log errors and warnings to syslog, else firma
#                will print errors to STDERR
# LOGGER_BINARY= if logging to syslog, set the path to logger's binary
# SYSLOG_PRIORITY= if logging to syslog, set a priority for the error messages
#                  (defaults to "user.err")
# USE_GPG_HIDDEN_RECIPIENT_OPTION= set to '1' to use GnuPG's --hidden-recipient
#                                  option, available from version 1.4.0 onwards
#                                  (try 'man gpg' for more information)
# REMOVE_THESE_HEADERS_ON_ALL_LISTS= headers that should be stripped from list
#                                    messages on all lists running under firma
#                                    (space separated case-insensitive entries)
#                                    (may include regexps (e.g., X-.*)
# KEYSERVER= default keyserver to import/export keys
#            (defaults to keyserver.noreply.org)
#
# And the list configuration file should contain:
#
# LIST_ADDRESS= list's email address
# LIST_ADMIN= list's administrators email addresses (space separated)
# LIST_HOMEDIR= list's GnuPG homedir, where the list's keyrings are located
# PASSPHRASE= passphrase for the list's private keyring
#
# And it may contain the following optional parameters:
#
# SUBJECT_PREFIX= prefix to be included in the subject of list messages
# REMOVE_THESE_HEADERS= headers that should be stripped from list messages
#                       (space separated case-insensitive entries)
#                       (may include regexps (e.g., X-.*)
# REPLIES_SHOULD_GO_TO_LIST= set to '1' to add a Reply-To header containing the
#                            list address
# SILENTLY_DISCARD_INVALID_MESSAGES= set to '1' to silently discard invalid
#                                    messages (message not signed/encrypted,
#                                    sender not subscribed to the list, etc.)
#                                    instead of sending bounces back to sender
# KEYSERVER= default keyserver to import/export keys
#            (defaults to keyserver.noreply.org)
#
# NOTE: The passphrase _has_ to be enclosed in single quotes and _cannot_
# contain any additional single quote as part of itself. It has to be at least
# 25 characters long, combining numbers, upper and lower case letters and at
# least 5 special characters. Also, no character can be sequentially repeated
# more than 4 times.
#

function Usage {
  #-------------------------------------------------------------
  # display help
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  # this will be printed to STDOUT, so no indentation here
  echo "\
Usage: $(basename $0) OPTION [LIST-NAME]
GnuPG-based encrypted mailing list manager.

  -a, --admin-task LIST-NAME        process administrative tasks on list
  -c, --create-newlist LIST-NAME    create a new mailing list
  -h, --help                        display this help and exit
  -p, --process-message LIST-NAME   process a message sent to list
  -v, --version                     output version information and exit

If option -a is given, read standard input for tasks to be performed.
Tasks can be one or more of the following:

  use EMAIL-ADDRESS   use the given address for message delivery instead
                        of the primary address on key

Report bugs to <firma@sarava.org>, encrypting the message using the pubkey
0xD68AFEDC available at keyserver.noreply.org."
}


function Version {
  #-------------------------------------------------------------
  # display version information
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  # this will be printed to STDOUT, so no indentation here
  echo "\
firma $VERSION

Copyright (C) 2005 A Firma, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the GNU General Public License
for more details."
}


function DeclareGpgVars {
  #-------------------------------------------------------------
  # declare gpg-related global variables
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------
  GPG_FLAGS="--no-options --no-default-keyring --homedir $LIST_HOMEDIR --quiet --batch --no-tty --no-use-agent --no-permission-warning"
  GPG="$GPG_BINARY $GPG_FLAGS"
  GPG_LIST_KEYS="$GPG --list-keys --with-colons"
  GPG_DECRYPT="$GPG --passphrase-fd 0 --decrypt"
  GPG_ENCRYPT="$GPG --armor --trust-model always --local-user $LIST_ADDRESS --passphrase-fd 0 --no-emit-version --sign --encrypt"
}


function CheckFirmaConfigFile {
  #-------------------------------------------------------------
  # check firma.conf parameters
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0 if all checks are passed,
  #          1 on any fatal errors
  #-------------------------------------------------------------

  local -i return_code=0

  if [[ ! -f "$GPG_BINARY" || ! -x "$GPG_BINARY" ]]; then
    ERROR_MESSAGE="FATAL: GPG binary ("$GPG_BINARY") could not be found. Quitting."
    return_code=1
  elif [[ ! -f "$MAIL_AGENT" || ! -x "$MAIL_AGENT" ]]; then
    ERROR_MESSAGE="FATAL: Mail transport agent binary ("$MAIL_AGENT") could not be found. Quitting."
    return_code=1
  elif [[ ! -d "$LISTS_DIR" ]]; then
    ERROR_MESSAGE="FATAL: Lists directory ("$LISTS_DIR") could not be found. Quitting."
    return_code=1
  elif [[ "$USE_GPG_HIDDEN_RECIPIENT_OPTION" == "1" && "$($GPG_BINARY --version | head -n1 | tr -dc '[[:digit:]]')" -lt "140" ]]; then
    ERROR_MESSAGE="\
WARNING: GPG's \"--hidden-recipient\" option is only available from version 1.4.0 onwards.
WARNING: Setting USE_GPG_HIDDEN_RECIPIENT_OPTION to '0'."
    USE_GPG_HIDDEN_RECIPIENT_OPTION=0
  elif [[ "$LOG_TO_SYSLOG" == "1" ]]; then
    if [[ ! -f "$LOGGER_BINARY" || ! -x "$LOGGER_BINARY" ]]; then
      ERROR_MESSAGE="\
WARNING: logger binary ("$LOGGER_BINARY") could not be found.
WARNING: Setting LOG_TO_SYSLOG to '0'."
      LOG_TO_SYSLOG=0
    fi
  fi

  if ! grep -q -e "^USER=" $FIRMA_CONFIG_FILE; then
    FIRMA_USER="nobody"
  else
    FIRMA_USER="`grep "^USER=" $FIRMA_CONFIG_FILE | sed -e 's/"//g' -e "s/'//g" | cut -d = -f 2`"
  fi

  if ! grep -q -e "^GROUP=" $FIRMA_CONFIG_FILE; then
    FIRMA_GROUP="nobody"
  else
    FIRMA_GROUP="`grep "^GROUP=" $FIRMA_CONFIG_FILE | sed -e 's/"//g' -e "s/'//g" | cut -d = -f 2`"
  fi

  if [ -z "$KEYSERVER" ]; then
    KEYSERVER="keyserver.noreply.org"
  fi

  return $return_code
}


function CheckListConfigFile {
  #-------------------------------------------------------------
  # check list configuration file parameters
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars
  # returns: 0 if all checks are passed,
  #          1 on any fatal errors
  #-------------------------------------------------------------

  local -i return_code=0
  local administrator
  local valid_admins

  if [[ ! -d "$LIST_HOMEDIR" || ! -f "$LIST_HOMEDIR/pubring.gpg" || ! -f "$LIST_HOMEDIR/secring.gpg" ]]; then
    ERROR_MESSAGE="FATAL: $LIST_NAME: GPG home directory ("$LIST_HOMEDIR") or the GPG keyrings could not be found. Quitting."
    return_code=1
#  elif [[ -z "$(grep -o "^PASSPHRASE='[^']*'$" $LIST_CONFIG_FILE)" || \
#         -z "$PASSPHRASE" || \
#         "$(echo "$PASSPHRASE" | wc -c)" -lt "25" || \
#         -z "$(echo "$PASSPHRASE" | tr -dc '[[:lower:]]')" || \
#         -z "$(echo "$PASSPHRASE" | tr -dc '[[:upper:]]')" || \
#         -z "$(echo "$PASSPHRASE" | tr -dc '[[:digit:]]')" || \
#         "$(echo "$PASSPHRASE" | tr -dc '[:punct:]' | wc -c)" -lt "5" || \
#         "$(echo "$PASSPHRASE" | fold -w1 | uniq -cd | grep -v '^ \{6\}[234] ')" ]]; then
#    ERROR_MESSAGE="$LIST_NAME: List passphrase is empty or does not meet the minimum complexity requirements"
#    return_code=1
  elif [[ -z "$($GPG --list-secret-keys --with-colons --fixed-list-mode "<$LIST_ADDRESS>" 2> /dev/null)" ]]; then
    ERROR_MESSAGE="FATAL: $LIST_NAME: Secret key for list "$LIST_ADDRESS" could not be found. Quitting."
    return_code=1
  else
    for administrator in $LIST_ADMIN; do {
      if [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$administrator>" 2> /dev/null | grep -v '^tru:')" ]]; then
        ERROR_MESSAGE="\
WARNING: $LIST_NAME: Public key for list administrator "$administrator" could not be found.
WARNING: $LIST_NAME: Removing this address from LIST_ADMIN."
      else
        valid_admins="$valid_admins $administrator"
      fi; }
    done
    LIST_ADMIN="$valid_admins"
  fi

  if grep -q -e "^USER=" $LIST_CONFIG_FILE; then
    FIRMA_USER="`grep "^USER=" $LIST_CONFIG_FILE | sed -e 's/"//g' -e "s/'//g" | cut -d = -f 2`"
  fi

  if grep -q -e "^GROUP=" $LIST_CONFIG_FILE; then
    FIRMA_GROUP="`grep "^GROUP=" $LIST_CONFIG_FILE | sed -e 's/"//g' -e "s/'//g" | cut -d = -f 2`"
  fi

  return $return_code
}


function GetMessage {
  #-------------------------------------------------------------
  # read message from STDIN
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0 on success,
  #          1 if there's no input
  #-------------------------------------------------------------

  local -i return_code=0

  # store message in ORIG_MESSAGE
  ORIG_MESSAGE="$(sed -ne '1,$p')"

  # check if message was successfully stored
  if [[ -z "$ORIG_MESSAGE" ]]; then
    ERROR_MESSAGE="FATAL: Message couldn't be read from standard input. Quitting."
    return_code=1
  fi

  return $return_code
}


function GetGpgMessage {
  #-------------------------------------------------------------
  # get the gpg encrypted part of the message
  #
  # parameter(s): none
  # depends on function(s): GetMessage
  # returns: 0 on success,
  #          1 if encrypted bloc can't be located within the message
  #-------------------------------------------------------------

  local -i return_code=0

  # find the first blank line in the message
  FIRST_BLANK_LINE=$(echo "$ORIG_MESSAGE" | grep -nm 1 '^$' | cut -d : -f 1)

  # then, find the beginning of the encrypted bloc
  if [[ -n $FIRST_BLANK_LINE ]]; then
    ENCRYPTED_BLOC_BEGINS=$(echo "$ORIG_MESSAGE" | grep -nm 1 -- '^-----BEGIN PGP MESSAGE-----' | cut -d : -f 1)

    # and then find the end of the bloc
    if [[ -n $ENCRYPTED_BLOC_BEGINS ]]; then
      ENCRYPTED_BLOC_ENDS=$(echo "$ORIG_MESSAGE" | grep -nm 1 -- '^-----END PGP MESSAGE-----' | cut -d : -f 1)

      # if there's an encrypted bloc, store it in ORIG_GPG_MESSAGE
      if [[ -n $ENCRYPTED_BLOC_ENDS ]]; then
        ORIG_GPG_MESSAGE="$(
          echo "$ORIG_MESSAGE" | \
          sed -ne "$((${ENCRYPTED_BLOC_ENDS} + 1))q;${ENCRYPTED_BLOC_BEGINS},${ENCRYPTED_BLOC_ENDS}p"
        )"
      fi
    fi
  fi

  # check if the bloc was successfully stored
  if [[ -z "$ORIG_GPG_MESSAGE" ]]; then
    ERROR_MESSAGE="No valid GPG encrypted bloc found within the message"
    return_code=1
  fi

  return $return_code
}


function ParseGpgDecryptStderr {
  #-------------------------------------------------------------
  # parse $GPG_DECRYPT STDERR for signature checking
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars, GetGpgMessage
  # returns: 0
  #-------------------------------------------------------------

  local gpg_decrypt_stderr

  # get GPG_DECRYPT STDERR, discarding its STDOUT
  gpg_decrypt_stderr="$(
    echo -e "${PASSPHRASE}\n${ORIG_GPG_MESSAGE}" | \
    ($GPG_DECRYPT --status-fd 2 1> /dev/null) 2>&1
  )"

  # check if message was encrypted with the list's public key
  if
    echo "$gpg_decrypt_stderr" | \
    grep -q "^\[GNUPG:] ENC_TO $(
      $GPG_LIST_KEYS $LIST_ADDRESS 2> /dev/null | \
      sed -ne '/:[sca]*[^e][sca]*:$/d' -e '/^sub:[^ired]:/p' | \
      cut -d : -f 5
    )"
  then
    ENCRYPTED_TO_LIST=1

    # if it was, check if its signature is valid
    if
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] GOODSIG'
    then
      GOOD_SIGNATURE=1

    # else, check if the signature is invalid (BAD signature)
    elif
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] BADSIG'
    then
      BAD_SIGNATURE=1

    # else, check if the signature couldn't be verified
    elif
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] ERRSIG'
    then
      SIGNATURE_CHECKING_FAILED=1

    # else, check if the message could at least be decrypted
    elif
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] DECRYPTION_OKAY'
    then
      MESSAGE_DECRYPTION_OKAY=1

    fi
  fi
}


function GetSubscribersList {
  #-------------------------------------------------------------
  # get list subscriber addresses for message encryption and delivery
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success,
  #          1 if there are no valid subscribers on list
  #-------------------------------------------------------------

  local -i return_code=0

  # get subscribers' email addresses, excluding invalid, revoked,
  #+expired and disabled keys, as well as any signing only keys
  SUBSCRIBERS_LIST="$(
    $GPG_LIST_KEYS 2> /dev/null | \
    sed -ne "/$LIST_ADDRESS/Id" -e '/:[scaeSCA]*[^E][scaeSCA]*:$/d' -e '/:[scaeSCAE]*D[scaeSCAE]*:$/d' -e '/^pub:[^ired]:/p' | \
    cut -d : -f 10 | \
    grep -o '<[^<>]*>$' | \
    sed -e 's/[<>]//g' | \
    sort -d
  )"

  # check if the list has valid subscribers
  if [[ -z "$SUBSCRIBERS_LIST" ]]; then
    ERROR_MESSAGE="FATAL: $LIST_NAME: No valid subscribers on list \"$LIST_ADDRESS\". Quitting."
    return_code=1
  fi

  return $return_code
}


function GetMessageHeadersAndBody {
  #-------------------------------------------------------------
  # store the message headers and body in two separate variables
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetGpgMessage
  # returns: 0
  #-------------------------------------------------------------

  # store everything up to the first blank line in ORIG_MESSAGE_HEADERS,
  #+unfolding any folded headers
  ORIG_MESSAGE_HEADERS="$(
    echo "$ORIG_MESSAGE" | \
    sed -ne "${FIRST_BLANK_LINE}q;1,$(($FIRST_BLANK_LINE - 1))p" | \
    sed -e :a -e '$!N;s/[ \t]*\n[ \t]\+/ /;ta' -e 'P;D'
  )"

  # store everything after this line in ORIG_MESSAGE_BODY
  ORIG_MESSAGE_BODY="$(
    echo "$ORIG_MESSAGE" | \
    sed -ne "$(($FIRST_BLANK_LINE + 1)),\$p"
  )"
}


function EditListMessageHeaders {
  #-------------------------------------------------------------
  # edit the headers of a list message, removing specific lines, adding
  #+a prefix to the Subject, etc
  #
  # parameter(s): none
  # depends on function(s): GetMessageHeadersAndBody
  # returns: 0
  #-------------------------------------------------------------

  local header
  local sed_args

  # remove headers as/if defined by firma configuration file
  if [[ -n "$REMOVE_THESE_HEADERS_ON_ALL_LISTS" ]]; then
    for header in $REMOVE_THESE_HEADERS_ON_ALL_LISTS; do
      sed_args="$sed_args -e /^${header}/Id"
    done

    MESSAGE_HEADERS="$(
      echo "$ORIG_MESSAGE_HEADERS" | \
      sed $sed_args
    )"
  fi

  # remove additional headers as/if defined by the list configuration file
  if [[ -n "$REMOVE_THESE_HEADERS" ]]; then

    # remove local variables contents, in case they have been used above
    header=''
    sed_args=''

    for header in $REMOVE_THESE_HEADERS; do
      sed_args="$sed_args -e /^${header}/Id"
    done

    MESSAGE_HEADERS="$(
      echo "$MESSAGE_HEADERS" | \
      sed $sed_args
    )"
  fi

  # insert/replace the Reply-To header
  if [[ -n "$REPLIES_SHOULD_GO_TO_LIST" ]]; then

    if ! echo "$MESSAGE_HEADERS" | \
         grep -iq '^Reply-To:'; then

      # these are the headers of the message to be sent, so no indentation here
      MESSAGE_HEADERS="\
$MESSAGE_HEADERS
Reply-To: $LIST_ADDRESS"

    else
      MESSAGE_HEADERS="$(
        echo "$MESSAGE_HEADERS" | \
        sed -e "s/^Reply-To:.*$/Reply-To: $LIST_ADDRESS/I"
      )"
    fi
  fi

  # insert the Subject prefix, if any
  if [[ -n "$SUBJECT_PREFIX" ]]; then

    # first, check if there's a Subject line
    if echo "$MESSAGE_HEADERS" | grep -iq '^Subject:'; then

      # and then check if the Subject already contains the list prefix
      if ! echo "$MESSAGE_HEADERS" | \
           grep -im 1 '^Subject:' | \
           grep -qF "$SUBJECT_PREFIX"; then

        # if it doesn't, insert it
        MESSAGE_HEADERS="$(
          echo "$MESSAGE_HEADERS" | \
          sed -e "s/^Subject:[ \t]*/Subject: $SUBJECT_PREFIX/I"
        )"
      fi

    # else, if there's no Subject line, add one containing only the list prefix
    else

      # these are the headers of the message to be sent, so no indentation here
      MESSAGE_HEADERS="\
$MESSAGE_HEADERS
Subject: $SUBJECT_PREFIX"

    fi
  fi
}


function DecryptGpgMessage {
  #-------------------------------------------------------------
  # decrypt the gpg encrypted part of the message
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars, GetGpgMessage
  # returns: 0
  #-------------------------------------------------------------

  DECRYPTED_MESSAGE="$(
    echo -e "${PASSPHRASE}\n${ORIG_GPG_MESSAGE}" | \
    $GPG_DECRYPT 2> /dev/null
  )"
}


function ReplaceGpgMessage {
  #-------------------------------------------------------------
  # replace the original encrypted bloc by one generated for the list subscribers
  #
  # parameter(s): none
  # depends on function(s): GetGpgMessage, GetMessageHeadersAndBody
  # returns: 0
  #-------------------------------------------------------------

  MESSAGE_BODY="$(
    echo "$ORIG_MESSAGE_BODY" | \
    sed -e "$(($ENCRYPTED_BLOC_BEGINS - $FIRST_BLANK_LINE)),$(($ENCRYPTED_BLOC_ENDS - $FIRST_BLANK_LINE))c $(
      echo "$GPG_MESSAGE" | \
      sed -e '$! s/$/\\/'
    )"
  )"
}


function GetSenderAddress {
  #-------------------------------------------------------------
  # get the sender address, needed for warning and bounce messages processing
  #
  # parameter(s): none
  # depends on function(s): GetMessage
  # returns: 0
  #-------------------------------------------------------------

  local from

  from=$(echo "$ORIG_MESSAGE" | grep -im 1 '^From:')
  SENDER_ADDRESS=$(
    if [[ -z "$(echo $from | grep '>$')" ]]; then
      echo $from
    else
      echo $from | grep -o '<[^<>]*>$' | sed -e 's/[<>]//g'
    fi
  )
}


function AssembleMessage {
  #-------------------------------------------------------------
  # just put the message headers and body together
  #
  # parameter(s): none
  # depends on function(s): EditListMessageHeaders, ReplaceGpgMessage,
  #                         ComposeAndSendWarningMessage,
  #                         ComposeAndSendBounceMessage
  # returns: 0
  #-------------------------------------------------------------

  # this is the actual message which will be sent, so no indentation here
  MESSAGE="\
$MESSAGE_HEADERS

$MESSAGE_BODY"

}


function ReEncryptAndSendListMessage {
  #-------------------------------------------------------------
  # send message to list subscribers
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars, DecryptGpgMessage,
  #                         GetSubscribersList, AssembleMessage
  # returns: 0
  #-------------------------------------------------------------

  local recipients
  local subscriber

  recipients="$(echo $SUBSCRIBERS_LIST)"

  # check if message should be encrypted and sent to all subscribers at once
  if [[ "$USE_GPG_HIDDEN_RECIPIENT_OPTION" == 1 ]]; then

    GPG_MESSAGE="$(
      echo -e "${PASSPHRASE}\n${DECRYPTED_MESSAGE}" | \
      $GPG_ENCRYPT --group subscribers="$recipients" --hidden-recipient subscribers 2> /dev/null
    )"

    ReplaceGpgMessage
    AssembleMessage

    # send message
    echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $recipients

  # else, message should be encrypted and sent to one subscriber at a time
  else
    for subscriber in $recipients; do

      GPG_MESSAGE="$(
        echo -e "${PASSPHRASE}\n${DECRYPTED_MESSAGE}" | \
        $GPG_ENCRYPT --recipient $subscriber
      )"

      ReplaceGpgMessage
      AssembleMessage

      # send message
      echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $subscriber

    done
  fi
}


function ComposeAndSendWarningMessage {
  #-------------------------------------------------------------
  # send a "BAD signature" warning to the list administrator(s) and to sender
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetSenderAddress, AssembleMessage
  # returns: 0
  #-------------------------------------------------------------

  local recipients

  recipients="$LIST_ADMIN $SENDER_ADDRESS"

  # these are the headers of the message to be sent, so no indentation here
  MESSAGE_HEADERS="\
From: $LIST_ADDRESS
Subject: BAD signature from $SENDER_ADDRESS
To: $SENDER_ADDRESS
Cc: $(echo $LIST_ADMIN | sed -e 's/ /, /g')"

  # this is the body of the message to be sent, so no indentation here
  MESSAGE_BODY="\
-------- Original Message --------
$ORIG_MESSAGE"

  AssembleMessage

  # send message
  echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $recipients
}


function ComposeAndSendBounceMessage {
  #-------------------------------------------------------------
  # send a bounce message back to sender
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetSenderAddress, AssembleMessage
  # returns: 0
  #-------------------------------------------------------------

  local subject

  subject="$(echo "$ORIG_MESSAGE" | grep -im 1 '^Subject:' | cut -d : -f 2- )"

  # these are the headers of the message to be sent, so no indentation here
  MESSAGE_HEADERS="\
From: $LIST_ADDRESS
Subject: [RETURNED MAIL]$subject
To: $SENDER_ADDRESS"

  # this is the body of the message to be sent, so no indentation here
  MESSAGE_BODY="\
$MESSAGE_BODY

-- 
firma"

  AssembleMessage

  # send message
  echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $SENDER_ADDRESS
}


function ProcessMessage {
  #-------------------------------------------------------------
  # process a received message
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetGpgMessage, GetSubscribersList,
  #                         GetSenderAddress
  # returns: 0 on success,
  #          1 if any of the above functions return an error
  #-------------------------------------------------------------

  local -i return_code=0

  # try to read message from STDIN
  if GetMessage; then

    # check if the message was encrypted
    if GetGpgMessage; then

      # if it was, parse gpg decrypt STDERR to decide what to do next
      ParseGpgDecryptStderr

      # if the message was encrypted with the list's public key and if the
      #+message signature is valid, send message to list subscribers
      if [[ $ENCRYPTED_TO_LIST == 1 && $GOOD_SIGNATURE == 1 ]]; then

        # check if the list has valid subscribers
        if GetSubscribersList; then

          GetMessageHeadersAndBody
          EditListMessageHeaders
          DecryptGpgMessage
          ReEncryptAndSendListMessage

        else
          return_code=1
        fi

      # else, if the message was correctly encrypted but its signature is invalid,
      #+send a warning about this to the list administrator(s) and to sender
      elif [[ $ENCRYPTED_TO_LIST == 1 && $BAD_SIGNATURE == 1 ]]; then

        GetSenderAddress

        if [[ -n $(echo $LIST_ADMINS) || -n "$SENDER_ADDRESS" ]]; then
          ComposeAndSendWarningMessage
        fi

      # else, a bounce should be sent
      else

        # if bounce processing is enabled, continue
        if [[ "$SILENTLY_DISCARD_INVALID_MESSAGES" != 1 ]]; then

          GetSenderAddress
          if [[ -n "$SENDER_ADDRESS" ]]; then

            # if the message was encrypted with the list's public key
            if [[ $ENCRYPTED_TO_LIST == 1 ]]; then

              # then, if signature can't be checked, then probably the sender is not subscribed to the list
              # send a bounce, if possible
              if [[ $SIGNATURE_CHECKING_FAILED == 1 ]]; then

                # this is the body of the message to be sent, so no indentation here
                MESSAGE_BODY="\
 It was not possible to process this message. Your email
 address is not subscribed to this list. Contact the list
 administrator if you have any questions."
                ComposeAndSendBounceMessage

              # or, if message can be decrypted but its signature can't be checked, then message wasn't signed
              # send a bounce, if possible
              elif [[ $MESSAGE_DECRYPTION_OKAY == 1 ]]; then

                # this is the body of the message to be sent, so no indentation here
                MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not signed. Contact the list administrator if you have any
 questions."
                ComposeAndSendBounceMessage
              fi

            # else, message wasn't encrypted with the list's public key
            # send a bounce, if possible
            else

              # this is the body of the message to be sent, so no indentation here
              MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not encrypted with the list's public key. Contact the list
 administrator if you have any questions."
              ComposeAndSendBounceMessage
            fi
          fi
        fi
      fi

    # else, message wasn't encrypted at all
    # send a bounce, if possible
    else

      # if bounce processing is enabled, continue
      if [[ "$SILENTLY_DISCARD_INVALID_MESSAGES" != 1 ]]; then

        GetSenderAddress
        if [[ -n "$SENDER_ADDRESS" ]]; then

          # this is the body of the message to be sent, so no indentation here
          MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not encrypted. Contact the list administrator if you have
 have any questions."
          ComposeAndSendBounceMessage
        fi
      fi
    fi

  # else, message could not be read from STDIN
  else
    return_code=1
  fi

  return $return_code
}


function NewList {
  #-------------------------------------------------------------
  # create a list if it doesn't exist yet
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success, 1 if list already exists or cannot be created
  #-------------------------------------------------------------

  local -i return_code=0
  local answer

  if [ ! -d "$LIST_PATH" ]; then

    echo "Creating folder $LIST_PATH..."
    if mkdir "$LIST_PATH"; then # || (echo "$(basename $0): error creating $LIST_PATH: installation aborted"; exit 1)
      echo "Creating list config file and will ask some questions."

    # TODO: try to create $LIST_HOMEDIR
    read -rep "  List keyring location: ("$LIST_PATH") " LIST_HOMEDIR
    LIST_HOMEDIR=${LIST_HOMEDIR:-"$LIST_PATH"}

    # Dont use UTF-8 (look at DETAILS)
    read -rep "  List email address: " LIST_ADDRESS
    read -rep "  List administrator(s) email address(es) (space delimited): " LIST_ADMIN
    read -rep "  List description (optional): " DESCRIPTION
    read -resp "  Passphrase to protect the list's secret key: " PASSPHRASE

    # TODO: automatically create a passphrase
    # TODO: key specs: size, expiry date...
    # TODO: CheckValidEmail $LIST_ADDRESS...
    # TODO: for admin in $LIST_ADMIN; do CheckValidEmail $admin...

    echo "Creating your config..."
    touch $LIST_CONFIG_FILE
    chmod 600 $LIST_CONFIG_FILE
    chown $FIRMA_USER.$FIRMA_GROUP $LIST_CONFIG_FILE
    if [ -f "$LIST_CONFIG_FILE" ]; then
      DeclareGpgVars
      # removed: MAIL_AGENT=$MAIL_AGENT\nGPG_BINARY=$GPG_BINARY\n
      echo -e "LIST_HOMEDIR='$LIST_HOMEDIR'\nLIST_ADDRESS='$LIST_ADDRESS'\nLIST_ADMIN='$LIST_ADMIN'\nPASSPHRASE='$PASSPHRASE'" > $LIST_CONFIG_FILE
      echo "Now generating your keyring..."

      $GPG --gen-key <<EOF

        Key-Type: DSA
        Key-Length: 1024
        Subkey-Type: ELG-E
        Subkey-Length: 1024

        Name-Real: $DESCRIPTION
        Name-Email: $LIST_ADDRESS

        Expire-Date: 0
        Passphrase: $PASSPHRASE
        %commit

EOF

      while true; do
        read -rep "  Send list public key to list admins? (Y/n) " answer
        answer="`echo $answer | tr '[:lower:]' '[:upper:]'`"
        if [ "$answer" == "Y" ] || [ "$answer" == "YES" ]; then
          SendListPubkey $LIST_ADMIN
          break
        elif [ "$answer" == "N" ] || [ "$answer" == "NO" ]; then
          echo "  Not sending public key from list to admins. Do it manually."
          break
        else
          echo "  Please answer either yes or no."
        fi
      done

      chown -R $FIRMA_USER.$FIRMA_GROUP $LIST_HOMEDIR

    else
      echo "$(basename $0): cannot create $LIST_PATH: Installation aborted"
      return_code=1
    fi

    fi
  else
    echo "$(basename $0): cannot create $LIST_NAME: List already exists"
    return_code=1
  fi

  return $return_code
}


function ListAdministration {
  #-------------------------------------------------------------
  # process administrative tasks
  #
  # parameter(s): task to be performed (plus its argument(s))
  # depends on function(s): ChooseUid, CheckValidEmail, UbsubscribeUser
  #                         SubscribeUsers, SendListPubkey
  # returns: 0 if task is executed successfully,
  #          1 if task can't be executed (command not found, too many/missing arguments, etc.),
  #          2 if a quit command is entered
  #-------------------------------------------------------------

  local -i return_code=0
  local subscribers

  case $# in
    1)
      case $1 in
        help)
          # this will be printed to STDOUT, so no indentation here
          echo "
  quit                 quit this prompt
  help                 show this help
  list                 show list subscribers
  info EMAIL-ADDRESS   show info of a given subscriber
  sendkey SUBSCRIBER   send list pubkey to subscriber
  subscribe [..]       subscribe users ('subscribe help' for options)
  use EMAIL-ADDRESS    use the given address for message delivery instead
                       of the primary address on key
  unsub EMAIL-ADDRESS  unsubscribe an email from the list
"
          ;;
        quit)
          return_code=3
          ;;
        use)
          echo >&2 "$1: missing arguments (try \"help\")"
          return_code=1
          ;;
        unsub)
          echo >&2 "$1: missing arguments (try \"help\")"
          return_code=1
          ;;
        list)
          GetSubscribersList
          for subscriber in $SUBSCRIBERS_LIST; do
            echo "  $subscriber"
          done
          ;;
        subscribe)
          echo >&2 "$1: missing arguments (try \"subscribe help\")"
          return_code=1 
          ;;
        sendkey)
          echo >&2 "$1: missing arguments (try \"sendkey help\")."
          return_code=1 
          ;;
        info)
          echo >&2 "$1: missing arguments (try \"info help\")."
          return_code=1 
          ;;
        *)
          echo >&2 "Command not found -- $1 (try \"help\")"
          return_code=1
          ;;
      esac
      ;;
    2)
      case $1 in
        use)
          # check if argument is an email address
          if CheckValidEmail $2; then
            ChooseUid $2
          else
            echo >&2 "$1: invalid argument -- $2 (try \"help\")"
            return_code=1
          fi
          ;;
        unsub)
          UnsubscribeUser $2
          return_code=$?
          ;;
        subscribe)
          SubscribeUsers $2
          return_code=$?
          ;;
        sendkey)
          SendListPubkey $2
          return_code=$?
          ;;
        info)
          GetSubscribersInfo $2
          return_code=$?
          ;;
        help|quit)
          echo >&2 "$1: too many arguments -- $@ (try \"help\")"
          return_code=1
          ;;
        *)
          echo >&2 "Command not found -- $1 (try \"help\")"
          return_code=1
          ;;
      esac
      ;;
    *)
      case $1 in
        help|quit|use)
          echo >&2 "$1: too many arguments -- $@ (try \"help\")"
          return_code=1
          ;;
        subscribe)
          shift
          SubscribeUsers $*
          return_code=$?
          ;;
        sendkey)
          shift
          SendListPubkey $*
          return_code=$?
          ;;
        info)
          shift
          GetSubscribersInfo $*
          return_code=$?
          ;;
        *)
          echo >&2 "Command not found -- $1 (try \"help\")"
          return_code=1
          ;;
      esac
      ;;
  esac

  return $return_code
}


function ChooseUid {
  #-------------------------------------------------------------
  # choose which UID of a public key should be used for message delivery,
  #+deleting all other UIDs on the key
  #
  # parameter(s): chosen email address
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success,
  #          1 if task can't be executed (public key not found, only one UID on key, etc.)
  #-------------------------------------------------------------

  local -i return_code=0
  local keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"
  local uid_count="$($GPG_LIST_KEYS --fixed-list-mode $keyid 2> /dev/null | grep ^uid | wc -l)"
  local chosen_uid_number="$($GPG_LIST_KEYS --fixed-list-mode $keyid 2> /dev/null | grep ^uid | grep -ni "$1" | cut -d : -f 1)"

  # check if supplied address is associated with a public key
  if [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$1>" 2> /dev/null | grep -v '^tru:')" ]]; then
    echo >&2 "use: \"$1\" is not associated with any public key on this keyring."
    return_code=1
  # then check if there's more than one UID on this public key
  elif (( "$($GPG_LIST_KEYS --fixed-list-mode $1 2> /dev/null | grep ^uid | wc -l)" == 1 )); then
    echo >&2 "use: \"$1\" is part of the only UID on public key ${keyid:32}."
    return_code=1
  # and then check if there's only one public key associated with this address
  elif (( "$($GPG_LIST_KEYS --fixed-list-mode $1 2> /dev/null | grep -i "<$1>:$" | wc -l)" > 1 )); then
    echo >&2 "use: \"$1\" is listed in more than one UID on this keyring."
    echo >&2 "Delete all but one of the public keys or UIDs associated with this email address."
    return_code=1
  fi

  # if all checks are OK, run the expect script bellow
  if (( $return_code == 0 )); then
    expect -nN -- << EOF
      # no output to STDOUT
      log_user 0
      # set a 5 seconds timeout in case anything goes wrong
      set timeout 5

      # call gpg with the "--edit-key" option
      eval spawn -noecho $GPG --with-colons --command-fd 0 --status-fd 1 --edit-key $keyid
      expect "GET_LINE keyedit.prompt" {
        # select for deletion all UIDs other than the chosen one
        set uid 1
        while { \$uid <= $uid_count } {
          if { \$uid != $chosen_uid_number } {
            send "uid \$uid\n"
            expect "GET_LINE keyedit.prompt"
          }
          set uid [incr uid]
        }
        # delete selected UIDs
        send "deluid\n"
        # confirm deletion
        expect "GET_BOOL keyedit.remove.uid.okay" {send "yes\n"}
        # save and exit
        expect "GET_LINE keyedit.prompt" {send "save\n"}
        expect "GOT_IT"
      }

      # delay until the process above terminates
      wait
      # send following message to user
      send_user "use: \"$1\" chosen for message delivery. [ expr $uid_count - 1 ] UID(s) deleted from public key ${keyid:32}.\n"
      exit
EOF
  fi

  return $return_code
}


function CheckPermission {
  #-------------------------------------------------------------
  # check if file has correct permissions (600) and also
  # +if the file is owned by $FIRMA_USER
  # +got the idea for this function from backupninja
  #
  # parameter(s): file name
  # depends on function(s): none
  # returns: 0 if file has correct permissions
  #          1 if not, and also print a warning message
  #-------------------------------------------------------------

  local file="$1"
  local perms="`ls -ld $file`"
  perms=${perms:4:6}
  if [ "$perms" != "------" ]; then
    LogMessage "WARNING: Configuration files must not be group or world writable/readable! Wrong permission for file $file"
    return 1
  fi

  if [ `ls -ld $file | awk '{print $3}'` != "$FIRMA_USER" ]; then
    echo "WARNING: Configuration files must be owned by $FIRMA_USER! Wrong ownership for file $file"
  fi

  return 0
}


function CheckListPermissions {
  #-------------------------------------------------------------
  # check if list files has correct permissions (600) and also
  # +if the files are owned by $FIRMA_USER
  #
  # parameter(s): list config file
  # depends on function(s): CheckPermission
  # returns: 0 if file has correct permissions
  #          1 if not, and also print a warning message
  #-------------------------------------------------------------

  local file
  local folder
  local config

  # check and fix permissions on all files from $LIST_PATH to $FIRMA_USER.$FIRMA_GROUP
  if [ ! -z "$1" ]; then
    folder="`dirname $1`"
    config="`basename $1`"
    for file in $config pubring.gpg pubring.gpg~ random_seed secring.gpg trustdb.gpg; do
      if ! CheckPermission $folder/$file; then
        LogMessage "Fixing permission and ownership for $folder/$file"
        chmod 600 $folder/$file
        chown $FIRMA_USER.$FIRMA_GROUP $folder/$file
      fi
    done
  fi
}


function CheckValidEmail {
  #-------------------------------------------------------------
  # check if argument is a valid email address
  #
  # parameter(s): string
  # depends on function(s): none
  # returns: 0 if string represents a valid email address
  #          1 if not
  #-------------------------------------------------------------

  if ! echo $1 | grep -q '[^@]\+@[^@]\+'; then
    return 1
  else
    return 0
  fi
}


function UnsubscribeUser {
  #-------------------------------------------------------------
  # unsubscribe a user and remove its pubkey from
  #+the list keyring
  #
  # parameter(s): chosen email address
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success,
  #          1 if task can't be executed (public key not found, etc.)
  #-------------------------------------------------------------

  local key
  local -i return_code=0
  local keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"

  # check if its a valid email
  if ! CheckValidEmail $1; then
    echo >&2 "unsub: \"$1\" is not an email address."
    return_code=1
  # check if user is trying to unsubscribe the list key
  elif [ "$1" == "$LIST_ADDRESS" ]; then
    echo >&2 "unsub: can't delete the list pubkey."
    return_code=1
  # check if supplied address is associated with a public key
  elif [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$1>" 2> /dev/null | grep -v '^tru:')" ]]; then
    echo >&2 "unsub: \"$1\" is not associated with any public key on this keyring."
    return_code=1
  else
    for key in $keyid; do
      $GPG --batch --delete-key --yes $key
      if [ "$?" == "0" ]; then
        echo >&2 "deleted key id $key for $1"
        # now just update the trust db
        $GPG_LIST_KEYS &> /dev/null
      else
        echo >&2 "unsub: error deleting key id $key for $1"
        return_code=1
      fi
    done
  fi

  FixListOwnership
  return $return_code
}


function LogMessage {
  #-------------------------------------------------------------
  # write a log message to stdout or to syslog
  #
  # parameter(s): string
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  local error_message
  error_message="$*"
  if [[ "$LOG_TO_SYSLOG" == 1 ]]; then
    echo "$error_message" | $LOGGER_BINARY -p "$SYSLOG_PRIORITY" -t "$BASENAME"
  else
    echo >&2 "$BASENAME: $error_message"
  fi

  return 0
}


function SubscribeUsers {
  #-------------------------------------------------------------
  # subscribe users to the list importing their pubkeys
  #
  # parameter(s): $1: help, stdin, keyserver or file
  #               $2: where to fetch the pubkeys
  #               $3: keyid (keyserver only)
  # depends on function(s): none
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  local -i return_code=0
  local keyserver
  local method

  if [ "$1" == "help" ]; then
    echo "
  help                                 show this help
  stdin                                waits for key material from stdin
  file <file-name>                     import pubkeys from file
  keyserver [server-address] <key-ids> import <key-ids> from <server-address>
"
  elif [ "$1" == "stdin" ]; then
    echo "please paste the key material here, finninshing with Ctrl-D sequence..."
    $GPG --import
  elif [ "$1" == "file" ]; then
    if [ ! -z "$2" ]; then
      if [ -f "$2" ]; then
        $GPG --import < $2
      else
        echo >&2 "subscribe: cant add subscribers from $1: no such file or directory"
        return_code=1
      fi
    else
      echo >&2 "subscribe: missing parameters: subscribe file requires a file name"
      return_code=1
    fi
  elif [ "$1" == "keyserver" ]; then
    if [ ! -z "$2" ]; then
      if [ -z "$3" ]; then
        keyserver="$KEYSERVER"
      else
        keyserver="$2"
        shift
      fi
      if CheckValidEmail $2; then
        method="--search-keys"
      else
        method="--recv-keys"
      fi
      shift
      $GPG --keyserver $keyserver $method $*
      return_code=$?
    else
      echo >&2 "subscribe: missing parameters: type subscribe help"
      return_code=1
    fi
  else
    echo >&2 "subscribe: wrong option: type subscribe help"
    return_code=1
  fi
  
  FixListOwnerShip
  return $return_code
}


function SendListPubkey {
  #-------------------------------------------------------------
  # send list pubkey to a given subscriber list
  #
  # parameter(s): subscribers' emails
  # depends on function(s): GetMessage, GetSenderAddress, AssembleMessage
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  local key
  local keys
  local keyid
  local boundary
  local keyboundary

  if [ "$1" == "help" ]; then
    echo "usage: sendkey [all|email|help]"
    echo "supported arguments: all (for all subscribers) or a space-separated subscriber emails."
    return 0
  elif [ "$1" == "all" ]; then 
    GetSubscribersList
    keys="$SUBSCRIBERS_LIST"
  else
    keys="$*"
  fi

  for key in $keys; do
    keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"

    if [ -z "$key" ]; then
      echo >&2 "sendkey: missing argument: subscriber email address."
      return 1
    elif ! CheckValidEmail $key; then
      echo >&2 "sendkey: \"$key\" is not an email address."
      return 1
    elif [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$key>" 2> /dev/null | grep -v '^tru:')" ]]; then
      # check if supplied address is associated with a public key
      echo >&2 "sendkey: \"$key\" is not associated with any public key on this keyring."
      return 1
    fi

    recipients="$key"
    boundary="`RandomString 15`"
    keyboundary="`RandomString 15`"

    # these are the headers of the message to be sent, so no indentation here
    MESSAGE_HEADERS="\
From: $LIST_ADDRESS
Subject: List public key for $LIST_ADDRESS
To: $recipients
MIME-Version: 1.0
Content-Type: multipart/encrypted;
  protocol=\"application/pgp-encrypted\";
  boundary=\"${boundary}\"
Content-Disposition: inline"

    # this is the body of the message to be sent, so no indentation here
    MESSAGE_BODY="`$GPG --armor --export $LIST_ADDRESS`"
    MESSAGE_BODY="\
Content-Type: multipart/mixed; boundary=\"$keyboundary\"
Content-Disposition: inline

--$keyboundary
Content-Type: application/pgp-keys
Content-Disposition: attachment
Content-Description: PGP Key for $LIST_ADDRESS

$MESSAGE_BODY

--${keyboundary}--"

    # now encrypt the message body
    MESSAGE_BODY="`echo -e "${PASSPHRASE}\n${MESSAGE_BODY}" | $GPG_ENCRYPT --recipient $recipients`"

    # this is the body of the message to be sent, so no indentation here
    MESSAGE_BODY="\
This is an OpenPGP/MIME encrypted message (RFC 2440 and 3156)
--$boundary
Content-Type: application/pgp-encrypted
Content-Description: PGP/MIME version identification

Version: 1

--$boundary
Content-Type: application/octet-stream; name=\"encrypted.asc\"
Content-Disposition: inline; filename=\"encrypted.asc\"

${MESSAGE_BODY}

--${boundary}--"

    AssembleMessage

    # send message
    echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $recipients
  done

}


function GetSubscribersInfo {
  #-------------------------------------------------------------
  # get info on a subscriber pubkey
  #
  # parameter(s): subscribers' emails
  # depends on function(s): none
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  local key
  local keys
  local keyid

  if [ "$1" == "help" ]; then
    echo "usage: info [all|email|help]"
    echo "supported arguments: all (for all subscribers) or a space-separated subscriber emails."
    return 0
  elif [ "$1" == "all" ]; then 
    GetSubscribersList
    keys="$SUBSCRIBERS_LIST"
  else
    keys="$*"
  fi

  for key in $keys; do
    keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"
    if [ ! -z "$keyid" ]; then
      $GPG --list-keys $key
    fi
  done

  return $?
}


function FixListOwnershipt {
  #-------------------------------------------------------------
  # fix list ownership
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  chown -R $FIRMA_USER.$FIRMA_GROUP $LIST_PATH
  return $?
}


function RandomString {
  #-------------------------------------------------------------
  # print a random string
  # +got it from http://funcoeszz.net/
  #
  # parameter(s): string size (max 62)
  # depends on function(s): none
  # returns: 0
  #          1 if string size is greater than 62
  #-------------------------------------------------------------

  local n alpha="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

  if [ -z "$1" ]; then
    n=6 
  else
    n=`echo "$1" | sed 's/[^0-9]//g'`
  fi

  if [ $n -gt 62 ]; then
    return 1
  fi

  while [ $n -ne 0 ]; do n=$((n-1)) ; pos=$((RANDOM%${#alpha}+1))
    echo -n "$alpha" | sed "s/\(.\)\{$pos\}.*/\1/"
    alpha=`echo $alpha | sed "s/.//$pos"`
  done | tr -d '\012' ; echo

  return 0

}

#-------------------------------------------------------------
# main()
#-------------------------------------------------------------

# path to firma.conf and firma version
FIRMA_CONFIG_FILE="/usr/local/etc/firma.conf"
VERSION="0.3"

# set environmental variables and options
export LANG=en_US
umask 0077

# declare global variables and functions used during execution
GLOBAL_VARS="
  GPG_BINARY MAIL_AGENT MAIL_AGENT_ARGS LISTS_DIR LOG_TO_SYSLOG LOGGER_BINARY SYSLOG_PRIORITY
  USE_GPG_HIDDEN_RECIPIENT_OPTION REMOVE_THESE_HEADERS_ON_ALL_LISTS SILENTLY_DISCARD_INVALID_MESSAGES
  LIST_ADDRESS LIST_ADMIN LIST_HOMEDIR PASSPHRASE SUBJECT_PREFIX REMOVE_THESE_HEADERS REPLIES_SHOULD_GO_TO_LIST
  FIRMA_CONFIG_FILE VERSION
  ERROR_MESSAGE EXIT_CODE
  DESCRIPTION LIST_NAME LIST_PATH LIST_CONFIG_FILE
  GPG_FLAGS GPG GPG_LIST_KEYS GPG_DECRYPT GPG_ENCRYPT
  STDIN
  ORIG_MESSAGE
  FIRST_BLANK_LINE ENCRYPTED_BLOC_BEGINS ENCRYPTED_BLOC_ENDS ORIG_GPG_MESSAGE
  ENCRYPTED_TO_LIST GOOD_SIGNATURE BAD_SIGNATURE SIGNATURE_CHECKING_FAILED MESSAGE_DECRYPTION_OKAY
  SUBSCRIBERS_LIST
  ORIG_MESSAGE_HEADERS ORIG_MESSAGE_BODY
  GPG_MESSAGE
  DECRYPTED_MESSAGE
  MESSAGE_HEADERS MESSAGE_BODY
  MESSAGE
  FUNCTION FUNCTIONS
  GLOBAL_VARS VAR
  USER
  GROUP
  BASENAME
  FIRMA_USER
  FIRMA_GROUP"

FUNCTIONS="
  Usage
  Version
  DeclareGpgVars
  CheckFirmaConfigFile
  CheckListConfigFile
  GetMessage
  GetGpgMessage
  ParseGpgDecryptStderr
  GetSubscribersList
  GetMessageHeadersAndBody
  EditListMessageHeaders
  DecryptGpgMessage
  ReplaceGpgMessage
  GetSenderAddress
  AssembleMessage
  ReEncryptAndSendListMessage
  ComposeAndSendWarningMessage
  ComposeAndSendBounceMessage
  ProcessMessage
  NewList
  ListAdministration
  ChooseUid
  CheckPermission
  CheckListPermissions
  UnsubscribeUser
  LogMessage
  SubscribeUsers
  SendListPubkey
  GetSubscribersInfo"

for VAR in $GLOBAL_VARS; do
  declare $VAR
done

# set initial exit code
EXIT_CODE=0

# set program name
BASENAME="`basename $0`"

# command line parsing:
# first check number of arguments, then check what was entered
# start main case
case $# in
  0)
    echo >&2 "$(basename $0): missing arguments"
    Usage
    EXIT_CODE=1
    ;;
  1)
    # start case #1
    case $1 in
      -h|--help)
        Usage
        EXIT_CODE=0
        ;;
      -v|--version)
        Version
        EXIT_CODE=0
        ;;
      # valid option called without its required argument
      -a|--admin-task|-c|--create-newlist|-p|--process-message)
        echo >&2 "$(basename $0): missing arguments"
        Usage
        EXIT_CODE=1
        ;;
      *)
        echo >&2 "$(basename $0): invalid option -- $1"
        Usage
        EXIT_CODE=1
        ;;
    # end case #1
    esac
    ;;
  2)
    # if firma.conf exists
    if [ -f "$FIRMA_CONFIG_FILE" ]; then

      # evaluate its parameters
      shopt -u sourcepath && source "$FIRMA_CONFIG_FILE"

      # set SYSLOG_PRIORITY to the default value, if needed
      if [[ "$LOG_TO_SYSLOG" == 1 ]]; then
        SYSLOG_PRIORITY=${SYSLOG_PRIORITY:-"user.err"}
      fi

      # and finally check firma.conf parameters and pessmissions
      if CheckFirmaConfigFile && CheckPermission $FIRMA_CONFIG_FILE; then

        LIST_NAME="$2"
        LIST_PATH="$LISTS_DIR/$LIST_NAME"
        LIST_CONFIG_FILE="$LIST_PATH/$LIST_NAME.conf"

        # start case #2
        case $1 in
          -c|--create-newlist)
            NewList
            ;;
          # options that depend on the list configuration file
          -a|--admin-task|-p|--process-message)

            # if config file exists but has wrong permissions or ownership
            if [[ -f "$LIST_CONFIG_FILE" ]]; then

              # if the configuration file exists, disable bash's
              #+sourcepath and evaluate list parameters
              shopt -u sourcepath && source "$LIST_CONFIG_FILE"

              CheckListPermissions $LIST_CONFIG_FILE

              # get gpg parameters
              DeclareGpgVars

              # check the list configuration file
              if CheckListConfigFile; then

                # start case #3
                case $1 in
                  -a|--admin-task)

                    # while a quit command isn't entered (returns 2), read STDIN
                    while (( $EXIT_CODE != 3 )) && read -rep "Command> " STDIN; do
                      # if line is not empty or commented, process command
                      if [[ -n "$STDIN" && "$STDIN" != "#"* ]]; then
                        ListAdministration $STDIN
                        EXIT_CODE=$?
                      fi
                    done

                    # since quit was entered, exit without error
                    EXIT_CODE=0

                    ;;
                  -p|--process-message)
                    ProcessMessage
                    EXIT_CODE=$?
                    ;;
                # end case #3
                esac
              # else, list configuration file checking returned an error
              else
                EXIT_CODE=$?
              fi
            # else, list configuration file could not be found
            else
              ERROR_MESSAGE="Cannot source \`$LIST_CONFIG_FILE': No such file or directory"
              EXIT_CODE=1
            fi
            ;;
          # valid option called with too many arguments
          -h|--help|-v|--version)
            echo >&2 "$(basename $0): too many arguments -- $@"
            Usage
            EXIT_CODE=1
            ;;
          *)
            echo >&2 "$(basename $0): invalid option -- $1"
            Usage
            EXIT_CODE=1
            ;;
        # end case #2
        esac
      # else, firma.conf checking returned an error
      else
        EXIT_CODE=$?
      fi
    # else, firma.conf could not be found
    else
      ERROR_MESSAGE="Cannot source \`$FIRMA_CONFIG_FILE': No such file or directory"
      EXIT_CODE=1
    fi
    ;;
  *)
    # start case #4
    case $1 in
      # again, valid option called with too many arguments
      -a|--admin-task|-c|--create-newlist|-h|--help|-p|--process-message|-v|--version)
        echo >&2 "$(basename $0): too many arguments -- $@"
        Usage
        EXIT_CODE=1
        ;;
      *)
        echo >&2 "$(basename $0): invalid option -- $1"
        Usage
        EXIT_CODE=1
        ;;
    # end case #4
    esac
    ;;
# end main case
esac

# print/log error message, if any
if [[ -n "$ERROR_MESSAGE" ]]; then
  LogMessage $ERROR_MESSAGE
fi

# erase all functions and global variables
for FUNCTION in $FUNCTIONS; do
  unset -f $FUNCTION
done

for VAR in $GLOBAL_VARS; do
  unset $VAR
done

# exit
exit $EXIT_CODE