-
Notifications
You must be signed in to change notification settings - Fork 0
/
signcontrol.py
executable file
·1484 lines (1294 loc) · 51.1 KB
/
signcontrol.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Script to help in managing Usenet hierarchies. It generates control articles
# and handles PGP keys (generation and management).
#
# signcontrol.py -- v. 1.5.0 -- 2023/10/29
#
# Original version written in 2007, and maintained since then by Julien ÉLIE
# in 2008, 2009, 2011, 2014, 2023, 2024.
#
#
# Github repository to view the latest source code and report possible issues:
# https://github.com/Julien-Elie/usenet-signcontrol/
#
# Please also read the Usenet hierarchy administration FAQ:
# https://www.eyrie.org/~eagle/faqs/usenet-hier.html
#
# SPDX-License-Identifier: MIT
#
# Feel free to use this script. I would be glad to know whether you find it
# useful for your hierarchy. Any bug reports, bug fixes, and improvements are
# very much welcome.
# Discussions about Usenet hierarchy administration in general take place in
# the news.admin.hierarchies newsgroup; do not hesitate to participate in this
# newsgroup!
#
#
# History:
#
# v. 1.5.1: (not yet released)
# - Switch ftp.isc.org's URLs to downloads.isc.org, the preferred
# hostname now that their FTP server has shut down.
# - Improve documentation (how to enable loopback pinentry mode to
# type the passphrase in a terminal, how to run inews, mention
# all the optional parameters).
#
# v. 1.5.0: 2023/10/29
# - Add compatibility with both Python 2 and Python 3.
# - Default encoding for generated control articles is now UTF-8
# in the configuration file (this charset SHOULD be used for
# non-ASCII characters, per Section 4.2 of RFC 5537). If you are
# upgrading from a previous version of signcontrol.py, and your
# checkgroups file contains descriptions with non-ASCII characters,
# you are encouraged to also switch to "UTF-8" as the value of the
# ENCODING parameter, use UTF-8 input in your terminal, and convert
# your checkgroups file to this charset.
# - Use --full-generate-key instead of --gen-key when generating a
# new pair of keys as GnuPG versions greater than 2.1.17 otherwise
# unconditionally set an expiration date.
# - Recommend at least a 3072-bit RSA key (and not a 2048-bit one).
# - Fix the feature of key revocation.
# - Colourize errors and recommendations in the terminal output to
# better view them.
# - Add the URL to the ftp.isc.org's README.html file in the X-Info
# header field only if not already present (it was previously
# unconditionally added).
# - Switch ftp.isc.org's URLs from ftp to https in the X-Info header
# field.
# - Improve documentation, with more details and return of
# experience accumulated since the last release.
#
# v. 1.4.0: 2014/10/26
# - Add the --no-tty flag to gpg when --passphrase is also used.
# Otherwise, an error occurs when running signcontrol.py from cron.
# Thanks to Matija Nalis for the bug report.
# - Add the PGP2_COMPATIBILITY parameter to generate control articles
# compatible with MIT PGP 2.6.2 (or equivalent).
# - When managing PGP keys, their full uid is now expected, instead
# of only a subpart.
# - Listing secret keys now also shows their fingerprint.
# - Improve documentation, along with the creation of a Git
# repository on Github.
#
# v. 1.3.3: 2011/07/11
# - Automatically generate an Injection-Date header field, and sign
# it. This will prevent control articles from being maliciously
# reinjected into Usenet, and replayed by news servers compliant
# with RFC 5537 (that is to say without cutoff on the Date header
# field when an Injection-Date header field exists).
#
# v. 1.3.2: 2009/12/23
# - Use local time instead of UTC (thanks to Adam H. Kerman for the
# suggestion).
# - Add flags to gpg when called: --emit-version, --no-comments,
# --no-escape-from-lines and --no-throw-keyids. Otherwise, the
# signature may not be valid (thanks to Robert Spier for the bug
# report).
#
# v. 1.3.1: 2009/12/20
# - Compliance with RFC 5322 (Internet Message Format): use "-0000"
# instead of "+0000" to indicate a time zone at Universal Time
# ("-0000" means that the time is generated on a system that may be
# in a local time zone other than Universal Time); also remove the
# Sender header field.
# - When a line in the body of a control article started with
# "Sender", a bug in signcontrol.py prevented the article from
# being properly signed.
#
# v. 1.3.0: 2009/07/28
# - Remove the charset for a multipart/mixed block in newgroup
# control articles.
# - Change the default serial number from 0 to 1 in checkgroups
# control articles.
# - Allow the user to interactively modify his message (thanks to
# Matija Nalis for the idea).
#
# v. 1.2.1: 2008/12/07
# - Ask for confirmation when "(Moderated)" is misplaced in a
# newsgroup description.
#
# v. 1.2.0: 2008/11/17
# - Support for RFC 5537: checkgroups scope, checkgroups serial
# numbers and accurate Content-Type header fields.
#
# v. 1.1.0: 2007/05/09
# - Fix the newgroups line when creating a newsgroup.
# - Use a separate config file.
# - Add the possibility to import signcontrol.py from other scripts
# and use its functions.
#
# v. 1.0.0: 2007/05/01
# - Initial release.
# THERE IS NOTHING USEFUL TO PARAMETERIZE IN THIS FILE.
# The file "signcontrol.conf" contains all your parameters. It will be parsed
# when running this script.
CONFIGURATION_FILE = "signcontrol.conf"
import os
import re
import shlex
import sys
import time
import traceback
# Current time.
TIME = time.localtime()
# Enable colours on Windows.
os.system("")
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
CYAN = "\033[36m"
END = "\033[0m"
def str_input(string):
"""Get a value from the user, using input() in Python 3 or raw_input() in
Python 2 as raw_input() is no longer defined in Python 3 (it was renamed
input() but has a different behaviour in Python 2).
Argument: string (the string to display)
Return value: the input from the user
"""
if sys.version_info[0] > 2:
return input(string)
else:
return raw_input(string)
def treat_exceptions(type, value, stacktrace):
"""Pretty print stack traces of this script, in case an error occurs.
Arguments: type (the type of the exception)
value (the value of the exception)
stacktrace (the traceback of the exception)
No return value (the script exits with status 2)
"""
print("-----------------------------------------------------------")
print("\n".join(traceback.format_exception(type, value, stacktrace)))
print("-----------------------------------------------------------")
str_input(RED + "An error has just occurred." + END)
sys.exit(2)
sys.excepthook = treat_exceptions
def print_error(error):
"""Pretty print error messages.
Argument: error (the error to print)
No return value
"""
print("")
print("--> " + RED + error + END + " <--")
print("")
def pretty_time(localtime):
"""Return the Date header field.
Argument: localtime (a time value, representing local time)
Return value: a string suitable to be used in a Date header field
"""
# As "%z" does not work on every platform with strftime(), we compute
# the time zone offset.
# You might want to use UTC with either "+0000" or "-0000", also changing
# time.localtime() to time.gmtime() for the definition of TIME above.
if localtime.tm_isdst > 0 and time.daylight:
offsetMinutes = -int(time.altzone / 60)
else:
offsetMinutes = -int(time.timezone / 60)
offset = "%+03d%02d" % (offsetMinutes / 60.0, offsetMinutes % 60)
return time.strftime("%a, %d %b %Y %H:%M:%S " + offset, localtime)
def serial_time(localtime):
"""Return a checkgroups serial number.
Argument: localtime (a time value, representing local time)
Return value: a string suitable to be used as a serial number
"""
# Note that there is only one serial per day.
return time.strftime("%Y%m%d", localtime)
def epoch_time(localtime):
"""Return the number of seconds since epoch.
Argument: localtime (a time value, representing local time)
Return value: the number of seconds since epoch, as a string
"""
return str(int(time.mktime(localtime)))
def read_configuration(file):
"""Parse the configuration file.
Argument: file (path to the signcontrol.conf configuration file)
Return value: a dictionary {parameter: value} representing
the contents of the configuration file
"""
TOKENS = [
"PROGRAM_GPG",
"PGP2_COMPATIBILITY",
"ID",
"MAIL",
"HOST",
"ADMIN_GROUP",
"NAME",
"CHECKGROUPS_SCOPE",
"URL",
"NEWGROUP_MESSAGE_MODERATED",
"NEWGROUP_MESSAGE_UNMODERATED",
"RMGROUP_MESSAGE",
"PRIVATE_HIERARCHY",
"CHECKGROUPS_FILE",
"ENCODING",
]
if not os.path.isfile(file):
print(RED + "The configuration file is absent." + END)
str_input("Please install it before using this script.")
sys.exit(2)
config_file = shlex.shlex(open(file, "r"), posix=True)
config = dict()
parameter = None
while True:
token = config_file.get_token()
if not token:
break
if token[0] in "\"'":
token = token[1:-1]
if token in TOKENS:
parameter = token
elif token != "=" and parameter:
if parameter == "PGP2_COMPATIBILITY":
if token == "True" or token == "true":
config[parameter] = [("--pgp2", "-pgp2"), ("", "")]
elif token == "Only" or token == "only":
config[parameter] = [("--pgp2", "-pgp2")]
else:
config[parameter] = [("", "")]
elif parameter == "PRIVATE_HIERARCHY":
if token == "True" or token == "true":
config[parameter] = True
else:
config[parameter] = False
else:
config[parameter] = token
parameter = None
for token in TOKENS:
if token not in config:
print("You must update the configuration file.")
print(RED + "The parameter " + token + " is missing." + END)
str_input(
"Please download the latest version of the configuration file"
" and parameterize it before using this script."
)
sys.exit(2)
return config
def read_checkgroups(path):
"""Parse a checkgroups file.
Argument: path (path of the checkgroups file)
Return value: a dictionary {newsgroup: description} representing
the contents of the checkgroups
"""
# Usually for the first use of the script.
if not os.path.isfile(path):
print("No checkgroups file found.")
print(GREEN + "Creating an empty checkgroups file..." + END)
write_checkgroups(dict(), path)
groups = dict()
for line in open(path):
line2 = line.strip()
while line2.find("\t\t") != -1:
line2 = line2.replace("\t\t", "\t")
try:
group, description = line2.split("\t")
groups[group] = description
except:
print_error(
RED + "The current checkgroups is incorrectly formatted." + END
)
print("The offending line is:")
print(line)
print("")
str_input("Please correct it before using this script.")
sys.exit(2)
return groups
def write_checkgroups(groups, path):
"""Write the current checkgroups file.
Arguments: groups (a dictionary representing a checkgroups)
path (path of the checkgroups file)
No return value
"""
keys = sorted(groups.keys())
checkgroups_file = open(path, "w")
for key in keys:
if len(key) < 8:
checkgroups_file.write(key + "\t\t\t" + groups[key] + "\n")
elif len(key) < 16:
checkgroups_file.write(key + "\t\t" + groups[key] + "\n")
else:
checkgroups_file.write(key + "\t" + groups[key] + "\n")
checkgroups_file.close()
print(GREEN + "Checkgroups file written." + END)
print("")
def choice_menu():
"""Print the initial menu, and waits for the user to make a choice.
Return value: the number representing the user's choice
"""
while True:
print(
"""
What do you want to do?
-----------------------
1. Generate a newgroup control article (create or change a newsgroup)
2. Generate an rmgroup control article (remove a newsgroup)
3. Generate a checkgroups control article (list of newsgroups)
4. Manage my PGP keys (generate/import/export/remove/revoke)
5. Quit
"""
)
try:
choice = int(str_input("Your choice (1-5): "))
if int(choice) not in list(range(1, 6)):
raise ValueError()
print("")
return choice
except:
print_error("Please enter a number between 1 and 5.")
def manage_menu():
"""Print the menu related to the management of PGP keys, and waits
for the user to make a choice.
Return value: the number representing the user's choice
"""
while True:
print(
"""
What do you want to do?
-----------------------
1. See the current installed keys
2. Generate a new pair of secret/public keys
3. Export a public key
4. Export a secret key
5. Import a secret key
6. Remove a pair of secret/public keys
7. Revoke a secret key
8. Quit
"""
)
try:
choice = int(str_input("Your choice (1-8): "))
if int(choice) not in list(range(1, 9)):
raise ValueError()
print("")
return choice
except:
print_error("Please enter a number between 1 and 8.")
def generate_signed_message(
config, file_message, group, message_id, type, passphrase=None, flag=""
):
"""Generate signed control articles.
Arguments: config (the dictionary of parameters from signcontrol.conf)
file_message (the file name of the message to sign)
group (the name of the newsgroup)
message_id (the Message-ID of the message)
type (the type of the control article)
passphrase (if given, the passphrase of the private key)
flag (if given, the additional flag(s) to pass to gpg)
No return value
"""
signatureWritten = False
if passphrase:
os.system(
config["PROGRAM_GPG"]
+ " --emit-version --no-comments --no-escape-from-lines"
' --no-throw-keyids --armor --detach-sign --local-user "='
+ config["ID"]
+ '" --no-tty --passphrase "'
+ passphrase
+ '" --output '
+ file_message
+ ".pgp "
+ flag
+ " "
+ file_message
+ ".txt"
)
else:
os.system(
config["PROGRAM_GPG"]
+ " --emit-version --no-comments --no-escape-from-lines"
' --no-throw-keyids --armor --detach-sign --local-user "='
+ config["ID"]
+ '" --output '
+ file_message
+ ".pgp "
+ flag
+ " "
+ file_message
+ ".txt"
)
if not os.path.isfile(file_message + ".pgp"):
print_error("Signature generation failed.")
print(RED + "Please verify the availability of the secret key." + END)
return
result = open(file_message + ".sig", "w")
for line in open(file_message + ".txt", "r"):
if signatureWritten:
result.write(line)
continue
if not line.startswith("X-Signed-Headers"):
# From is the last signed header field.
if not line.startswith("From"):
result.write(line)
else:
# Rewrite the From line exactly as we already wrote it.
result.write(
"From: " + config["NAME"] + " <" + config["MAIL"] + ">\n"
)
result.write("Approved: " + config["MAIL"] + "\n")
if type == "checkgroups" and not config["PRIVATE_HIERARCHY"]:
result.write(
"Newsgroups: " + group + ",news.admin.hierarchies\n"
)
result.write("Followup-To: " + group + "\n")
else:
result.write("Newsgroups: " + group + "\n")
result.write("Path: not-for-mail\n")
result.write("X-Info: ")
if config["URL"]:
result.write(config["URL"] + "\n")
if (
"https://downloads.isc.org/pub/pgpcontrol/README.html"
not in config["URL"]
and "https://ftp.isc.org/pub/pgpcontrol/README.html"
not in config["URL"]
):
if config["URL"]:
result.write("\t")
result.write(
"https://downloads.isc.org/pub/pgpcontrol/README.html\n"
)
result.write("MIME-Version: 1.0\n")
if type == "newgroup":
result.write(
"Content-Type: multipart/mixed;"
' boundary="signcontrol"\n'
)
elif type == "checkgroups":
result.write(
"Content-Type: application/news-checkgroups; charset="
+ config["ENCODING"]
+ "\n"
)
else: # rmgroup
result.write(
"Content-Type: text/plain; charset="
+ config["ENCODING"]
+ "\n"
)
result.write("Content-Transfer-Encoding: 8bit\n")
for line2 in open(file_message + ".pgp", "r"):
if line2.startswith("-"):
continue
if line2.startswith("Version:"):
version = line2.replace("Version: ", "")
version = version.replace(" ", "_")
result.write(
"X-PGP-Sig: "
+ version.rstrip()
+ " Subject,Control,Message-ID,Date"
+ ",Injection-Date,From\n"
)
elif len(line2) > 2:
result.write("\t" + line2.rstrip() + "\n")
signatureWritten = True
result.close()
os.remove(file_message + ".pgp")
print("")
if flag:
print(
YELLOW
+ "Do not worry if the program complains about detached signatures"
" or MD5." + END
)
print("You can now post the file " + file_message + ".sig using rnews")
print("or a similar tool.")
print("")
# print("Or you can also try to send it with IHAVE. If it fails,"
# " it means that the article")
# print("has not been sent. You will then have to manually use rnews"
# " or a similar program.")
# if str_input("Do you want to try? (y/n) ") == "y":
# import nntplib
# news_server = nntplib.NNTP(HOST, PORT, USER, PASSWORD)
# news_server.ihave(message_id, file_message + ".sig")
# news_server.quit()
# print("The control article has just been sent!")
def sign_message(
config, file_message, group, message_id, type, passphrase=None
):
"""Sign a control article.
Arguments: config (the dictionary of parameters from signcontrol.conf)
file_message (the file name of the message to sign)
group (the name of the newsgroup)
message_id (the Message-ID of the message)
type (the type of the control article)
passphrase (if given, the passphrase of the private key)
No return value
"""
articles_to_generate = len(config["PGP2_COMPATIBILITY"])
i = 1
for flag, suffix in config["PGP2_COMPATIBILITY"]:
if articles_to_generate > 1:
print("")
print(
"Generation of control article "
+ str(i)
+ "/"
+ str(articles_to_generate)
)
i += 1
if suffix:
additional_file = open(file_message + suffix + ".txt", "w")
additional_message_id = message_id.replace("@", suffix + "@", 1)
for line in open(file_message + ".txt", "r"):
if line == "Message-ID: " + message_id + "\n":
line = "Message-ID: " + additional_message_id + "\n"
additional_file.write(line)
additional_file.close()
generate_signed_message(
config,
file_message + suffix,
group,
additional_message_id,
type,
passphrase,
flag,
)
os.remove(file_message + suffix + ".txt")
else:
generate_signed_message(
config, file_message, group, message_id, type, passphrase, flag
)
def generate_newgroup(
groups,
config,
group=None,
moderated=None,
description=None,
message=None,
passphrase=None,
):
"""Create a new group.
Arguments: groups (the dictionary representing the checkgroups)
config (the dictionary of parameters from signcontrol.conf)
group (if given, the name of the newsgroup)
moderated (if given, whether the newsgroup is moderated)
description (if given, the description of the newsgroup)
message (if given, the text to write in the control article)
passphrase (if given, the passphrase of the private key)
No return value
"""
while not group:
group = str_input("Name of the newsgroup to create: ").lower()
components = group.split(".")
if len(components) < 2:
group = None
print_error("The group must have at least two components.")
elif not components[0][0:1].isalpha():
group = None
print_error("The first component must start with a letter.")
elif components[0] in ["control", "example", "to"]:
group = None
print_error(
'The first component must not be "control", "example" or "to".'
)
elif re.search("[^a-z0-9+_.-]", group):
group = None
print_error(
"The group must not contain characters other than"
" [a-z0-9+_.-]."
)
for component in components:
if component in ["all", "ctl"]:
group = None
print_error(
'Sequences "all" and "ctl" must not be used as components.'
)
elif not component[0:1].isalnum():
group = None
print_error(
"Each component must start with a letter or a digit."
)
elif component.isdigit():
group = None
print_error(
"Each component must contain at least one non-digit"
" character."
)
if group in groups:
print(
"""
The newsgroup %s already exists.
These new settings (status and description) will override the current ones.
"""
% group
)
if moderated is None:
if str_input("Is " + group + " a moderated newsgroup? (y/n) ") == "y":
moderated = True
print(
YELLOW
+ """
There is no need to add " (Moderated)" at the very end of the description.
It will be automatically added, if not already present."""
+ END
)
else:
moderated = False
while not description:
print("")
print(
YELLOW + "The description should start with a capital and end in a"
" period." + END
)
description = str_input("Description of " + group + ": ")
if len(description) > 56:
print_error("The description is too long. You should shorten it.")
if (
str_input(
"Do you want to continue despite this recommendation?"
" (y/n) "
)
!= "y"
):
description = None
continue
moderated_count = description.count("(Moderated)")
if moderated_count > 0:
if not moderated:
if description.endswith(" (Moderated)"):
description = None
print_error(
'The description must not end with " (Moderated)".'
)
continue
else:
print_error(
'The description must not contain "(Moderated)".'
)
if (
str_input(
"Do you want to continue despite this"
" recommendation? (y/n) "
)
!= "y"
):
description = None
continue
elif moderated_count > 1 or not description.endswith(
" (Moderated)"
):
print_error('The description must not contain "(Moderated)".')
if (
str_input(
"Do you want to continue despite this recommendation?"
" (y/n) "
)
!= "y"
):
description = None
continue
if not message:
print("")
print("The current message which will be sent is:")
print("")
if moderated:
message = config["NEWGROUP_MESSAGE_MODERATED"].replace(
"$GROUP$", group
)
else:
message = config["NEWGROUP_MESSAGE_UNMODERATED"].replace(
"$GROUP$", group
)
print(CYAN + message + END)
print("")
if str_input("Do you want to change it? (y/n) ") == "y":
print("")
print("Please enter the message you want to send.")
print(
YELLOW
+ 'End it with a line containing only "." (a dot).'
+ END
)
print("")
message = ""
buffer = str_input("Message: ") + "\n"
while buffer != ".\n":
message += buffer.rstrip() + "\n"
buffer = str_input("Message: ") + "\n"
print("")
print("Here is the information about the newsgroup:")
print("")
print("Name: " + CYAN + group + END)
if moderated:
print("Status: " + CYAN + "moderated" + END)
if not description.endswith(" (Moderated)"):
description += " (Moderated)"
else:
print("Status: " + CYAN + "unmoderated" + END)
print("Description: " + CYAN + description + END)
print("Message: ")
print("")
print(CYAN + message + END)
print("")
if (
str_input(
"Do you want to generate a control article for "
+ group
+ "? (y/n) "
)
== "y"
):
print("")
file_newgroup = group + "-" + epoch_time(TIME)
result = open(file_newgroup + ".txt", "w")
result.write(
"X-Signed-Headers:"
" Subject,Control,Message-ID,Date,Injection-Date,From\n"
)
if moderated:
result.write("Subject: cmsg newgroup " + group + " moderated\n")
result.write("Control: newgroup " + group + " moderated\n")
else:
result.write("Subject: cmsg newgroup " + group + "\n")
result.write("Control: newgroup " + group + "\n")
message_id = (
"<newgroup-"
+ group
+ "-"
+ epoch_time(TIME)
+ "@"
+ config["HOST"]
+ ">"
)
result.write("Message-ID: " + message_id + "\n")
result.write("Date: " + pretty_time(TIME) + "\n")
result.write("Injection-Date: " + pretty_time(TIME) + "\n")
result.write(
"From: " + config["NAME"] + " <" + config["MAIL"] + ">\n\n"
)
result.write("This is a MIME NetNews control message.\n")
result.write("--signcontrol\n")
result.write(
"Content-Type: text/plain; charset=" + config["ENCODING"] + "\n\n"
)
result.write(message + "\n")
result.write("\n\n--signcontrol\n")
result.write(
"Content-Type: application/news-groupinfo; charset="
+ config["ENCODING"]
+ "\n\n"
)
result.write("For your newsgroups file:\n")
if len(group) < 8:
result.write(group + "\t\t\t" + description + "\n")
elif len(group) < 16:
result.write(group + "\t\t" + description + "\n")
else:
result.write(group + "\t" + description + "\n")
result.write("\n--signcontrol--\n")
result.close()
sign_message(
config, file_newgroup, group, message_id, "newgroup", passphrase
)
os.remove(file_newgroup + ".txt")
if (
str_input("Do you want to update the current checkgroups file? (y/n) ")
== "y"
):
groups[group] = description
write_checkgroups(groups, config["CHECKGROUPS_FILE"])
def generate_rmgroup(
groups, config, group=None, message=None, passphrase=None
):
"""Remove a group.
Arguments: groups (the dictionary representing the checkgroups)
config (the dictionary of parameters from signcontrol.conf)
group (if given, the name of the newsgroup)
message (if given, the text to write in the control article)
passphrase (if given, the passphrase of the private key)
No return value
"""
while not group:
group = str_input("Name of the newsgroup to remove: ").lower()
if group not in groups:
print("")
print(YELLOW + "The newsgroup " + group + " does *not* exist." + END)
print("Yet, you can send an rmgroup message for it if you want.")
print("")
if (
str_input(
"Do you want to generate a control article to *remove* "
+ group
+ "? (y/n) "
)
== "y"
):
print("")
if not message:
print("The current message which will be sent is:")
print("")
message = config["RMGROUP_MESSAGE"].replace("$GROUP$", group)
print(CYAN + message + END)
print("")
if str_input("Do you want to change it? (y/n) ") == "y":
print("")
print("Please enter the message you want to send.")
print(
YELLOW
+ 'End it with a line containing only "." (a dot).'
+ END
)
print("")
message = ""
buffer = str_input("Message: ") + "\n"
while buffer != ".\n":
message += buffer.rstrip() + "\n"
buffer = str_input("Message: ") + "\n"
print("")
file_rmgroup = group + "-" + epoch_time(TIME)
result = open(file_rmgroup + ".txt", "w")
result.write(
"X-Signed-Headers:"
" Subject,Control,Message-ID,Date,Injection-Date,From\n"
)
result.write("Subject: cmsg rmgroup " + group + "\n")
result.write("Control: rmgroup " + group + "\n")
message_id = (
"<rmgroup-"
+ group
+ "-"
+ epoch_time(TIME)
+ "@"
+ config["HOST"]
+ ">"
)
result.write("Message-ID: " + message_id + "\n")
result.write("Date: " + pretty_time(TIME) + "\n")
result.write("Injection-Date: " + pretty_time(TIME) + "\n")
result.write(
"From: " + config["NAME"] + " <" + config["MAIL"] + ">\n\n"
)
result.write(message + "\n")
result.close()
sign_message(
config, file_rmgroup, group, message_id, "rmgroup", passphrase
)
os.remove(file_rmgroup + ".txt")
if group in groups:
if (
str_input(
"Do you want to update the current checkgroups file? (y/n) "
)
== "y"
):
del groups[group]
write_checkgroups(groups, config["CHECKGROUPS_FILE"])
def generate_checkgroups(config, passphrase=None, serial=None):
"""List the groups of the hierarchy.
Arguments: config (the dictionary of parameters from signcontrol.conf)
passphrase (if given, the passphrase of the private key)
serial (if given, the serial value to use)
No return value
"""
while serial not in list(range(0, 100)):
try:
print(
"If it is your first checkgroups for today, leave it blank"
" (default is 1)."
)
print("Otherwise, increment this revision number by one.")
serial = int(str_input("Revision to use (1-99): "))
print("")
except:
serial = 1
serial = "%02d" % serial
file_checkgroups = "checkgroups-" + epoch_time(TIME)
result = open(file_checkgroups + ".txt", "w")
result.write(
"X-Signed-Headers:"
" Subject,Control,Message-ID,Date,Injection-Date,From\n"
)
result.write(
"Subject: cmsg checkgroups "
+ config["CHECKGROUPS_SCOPE"]
+ " #"
+ serial_time(TIME)
+ serial
+ "\n"
)
result.write(
"Control: checkgroups "
+ config["CHECKGROUPS_SCOPE"]
+ " #"
+ serial_time(TIME)
+ serial
+ "\n"
)
message_id = (
"<checkgroups-" + epoch_time(TIME) + "@" + config["HOST"] + ">"
)
result.write("Message-ID: " + message_id + "\n")
result.write("Date: " + pretty_time(TIME) + "\n")
result.write("Injection-Date: " + pretty_time(TIME) + "\n")
result.write("From: " + config["NAME"] + " <" + config["MAIL"] + ">\n\n")
for line in open(config["CHECKGROUPS_FILE"], "r"):
result.write(line.rstrip() + "\n")