-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPyPacketMail.py
919 lines (735 loc) · 30.7 KB
/
PyPacketMail.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
#!/usr/bin/env python2.7
"""
PyPacketMail for x/84, http://github.com/jquast/x84
(c) 2015 Michael Griffin <[email protected]>
http://github.com/m-griffin/PyMailPacket
This is a FidoNet Echomail Scanner / Tosser for x84 bbs.
This will mimic the basic functionality of Crashmail for
Reading and Writing mail packets.
*** Sample INI Section to be added to DEFAULT.INI in X84
# Setup for PyPacket Mail {Fidonet Tosser/Scanner}
[mailpacket]
inbound = /home/pi/Desktop/PyPacketMail/inbound
outbound = /home/pi/Desktop/PyPacketMail/outbound
pack = /home/pi/Desktop/PyPacketMail/pack
unpack = /home/pi/Desktop/PyPacketMail/unpack
bad = /home/pi/Desktop/PyPacketMail/bad
archive = /home/pi/Desktop/PyPacketMail/archive
# Fido Type Network Domain names, seperate with commas.
[fido_networks]
network_tags = agoranet, fidonet
# Network Specific Addresses and Area -> Tag Translations.
[agoranet]
node_address = 46:1/140
export_address = 46:1/100
areas = agn_gen: general, agn_ads: bbs_ads, agn_bbs: bbs_discussion, agn_art: art, agn_dev: development,
agn_nix: unix_linux, agn_hub: hub_stats, agn_l46: league46, agn_tst: testing, agn_sys: sysop_area
default_area = agn_gen
# Network Specific Addresses and Area -> Tag Translations.
[fidonet]
node_address = 1:154/140
export_address = 1:154/10
areas = fdn_ent: enthral_bbs
default_area = fdn_ent
Recent changeLog
* 0.0.1
- Added Default Areas, of only a network tag is used eg. agoranet, and no
specific area tag is selected. the default_area will then be used for
exporting messages.
"""
__author__ = "Michael Griffin"
__copyright__ = "Copyright 2015"
__credits__ = "Jeff Quast"
__license__ = "MIT"
__version__ = "1.0.0"
__status__ = "Prototype"
import collections
import datetime
import zipfile
import struct
import glob
import os
# Reading Binary Packet Formats
from ctypes import LittleEndianStructure, Union, c_uint8
# x84 specific
from x84.bbs.ini import init, get_ini
from x84.cmdline import parse_args
# Database for holding FidoNet Specific Items and Kludges
FIDO_DB = 'pymail'
# Read in default .x84 INI File.
init(*parse_args())
class FidonetConfiguration():
# Holds configuration values from x84 Default.ini
# also builds up lists of areas per network and
# their data -> tag translatons
def __init__(self):
self.__network_list = [] # List of Fido Networks
self.__node_address = {} # Your Address
self.__export_address = {} # Your Network Hub's Address
self.__network_areas = {} # Message Areas by network
self.__default_areas = {} # Default if no Valid Area Tag
self.__inbound_folder = None
self.__unpack_folder = None
self.read_configuration() # Load All INI settings on startup.
def add_network(self):
# Everything is built from the initial network address
self.__network_list = \
get_ini(section='fido_networks', key='network_tags', split=True)
def add_node_address(self):
# Node Addresses per network
if self.is_network_empty is False:
for net in self.__network_list:
# Loop network list and get network section.
self.__node_address[net] = \
get_ini(section=net, key='node_address', split=True)
def add_export_address(self):
# Export {mail hub} addresses per network
if self.is_network_empty is False:
for net in self.__network_list:
# Loop network list and get network section.
self.__export_address[net] = \
get_ini(section=net, key='export_address', split=True)
def add_network_areas(self):
# key value area to tag translations per network
if self.is_network_empty is False:
for net in self.__network_list:
# Loop network list and get network section.
self.__network_areas[net] = \
get_ini(section=net, key='areas', split=True)
def add_default_areas(self):
# No Valid area, then use default area
if self.is_network_empty is False:
for net in self.__network_list:
# Loop network list and get network section.
self.__default_areas[net] = \
get_ini(section=net, key='default_area', split=True)
@property
def is_network_empty(self):
if bool(self.__network_list and True):
return False
return True
@property
def inbound_folder(self):
return self.__inbound_folder
@property
def unpack_folder(self):
return self.__unpack_folder
def check_network_address(self, address):
# verify node address, return network name
for key, val in self.__node_address.items():
if address in ''.join(val):
return '{network}'.format(network=key)
return None
def get_tag(self, network_name, network_area):
# transpose area to tag name
# seperate string value into k, v dist.
if self.is_network_empty is False:
for area in self.__network_areas[network_name]:
k, v = area.split(': ')
if network_area in k:
return v
return None
def count_network_areas(self):
# Just gets a general count of network keys
# should have at least 1 network with a value area string.
count = 0
if self.is_network_empty is False:
count = len(self.__network_areas)
return count
def read_configuration(self):
# Working Folders pull from .x84 Default INI
self.__inbound_folder = ''.join(get_ini(section='mailpacket', key='inbound', split=True))
self.__unpack_folder = ''.join(get_ini(section='mailpacket', key='unpack', split=True))
# read .x84 default.ini file for network info
# build dicts for all networks and their associations
self.add_network()
print 'network_list: ' + ', '.join(str(x) for x in self.__network_list)
self.add_node_address()
for key, val in self.__node_address.items():
print 'node_address: {key}, {value}'.format(key=key, value=val)
self.add_export_address()
for key, val in self.__export_address.items():
print 'export_address: {key}, {value}'.format(key=key, value=val)
self.add_network_areas()
for key, val in self.__network_areas.items():
print 'network_areas: {key}, {value}'.format(key=key, value=val)
self.add_default_areas()
for key, val in self.__default_areas.items():
print 'default_areas: {key}, {value}'.format(key=key, value=val)
print ''
# Parse and Setup Fido-net addresses and areas
cfg = FidonetConfiguration()
print ''
print 'is network empty: {bool}'.format(bool=cfg.is_network_empty)
print 'num of network w/ areas: {count}'.format(count=cfg.count_network_areas())
print 'inbound_folder: {name}'.format(name=cfg.inbound_folder)
print 'unpack_folder : {name}'.format(name=cfg.unpack_folder)
print ''
# Make sure we have at least one network setup
assert cfg.is_network_empty is False
# Make sure we have at least one network area
assert cfg.count_network_areas() >= 1
# Make sure the Inbound directory is valid
assert os.path.isdir(cfg.inbound_folder)
# Check the Packet Folder.
assert os.path.isdir(cfg.unpack_folder)
# Handle count of Areas Processed
area_count = collections.defaultdict(int)
# Fido Packet 2 Structure
_struct_packet_header_fields = [
# Structure Size 58
('H', 'origin_node'),
('H', 'destination_node'),
('H', 'year'),
('H', 'month'),
('H', 'day'),
('H', 'hour'),
('H', 'minute'),
('H', 'second'),
('H', 'baud'),
('H', 'packet_type'),
('H', 'origin_network'),
('H', 'destination_network'),
('B', 'prod_code_low'),
('B', 'revision_major'),
('8s', 'password'),
('H', 'origin_zone'),
('H', 'destination_zone'),
('H', 'aux_network'),
('H', 'capWordA'),
('B', 'prod_code_hi'),
('B', 'revision_minor'),
('H', 'capWordB'),
('H', 'origin_zone2'),
('H', 'destination_zone2'),
('H', 'origin_point'),
('H', 'destination_point'),
('L', 'prod_data')
]
_struct_fidonet_packet = '<{0}'.format(
''.join(struct_val for struct_val, _ in _struct_packet_header_fields))
FidonetPacketHeader = collections.namedtuple(
'FidonetPacketHeader', [field_name for _, field_name in _struct_packet_header_fields])
class FlagBits(LittleEndianStructure):
# Captures the 1st Byte Set of Bit Flags in the Message Header
_fields_ = [
('private', c_uint8, 1), # asByte & 1
('crash', c_uint8, 1), # asByte & 2
('received', c_uint8, 1), # asByte & 4
('sent', c_uint8, 1), # asByte & 8
('file_attach', c_uint8, 1), # asByte & 16
('in_transit', c_uint8, 1), # asByte & 32
('orphan', c_uint8, 1), # asByte & 64
('kill_sent', c_uint8, 1), # asByte & 128
]
def get_dict(self):
# return ordered fields of bits
return collections.OrderedDict((f, getattr(self, f)) for f, v, i in self._fields_)
class FlagBits2(LittleEndianStructure):
# Captures the 2nd Byte Set of Bit Flags in the Message Header
_fields_ = [
('local', c_uint8, 1), # asByte & 256
('hold', c_uint8, 1), # asByte & 512
('unused', c_uint8, 1), # asByte & 1024
('file_request', c_uint8, 1), # asByte & 2048
('want_receipt', c_uint8, 1), # asByte & 4096
('is_receipt', c_uint8, 1), # asByte & 8192
('audit', c_uint8, 1), # asByte & 16384
('file_update', c_uint8, 1), # asByte & 32768
]
def get_dict(self):
# return ordered fields of bits
return collections.OrderedDict((f, getattr(self, f)) for f, v, i in self._fields_)
class Flags(Union):
# Union to set the In_Value flips the appropriate bits flags
# in_value can also be used to get the value of all set flags
_fields_ = [('bit', FlagBits),
('in_value', c_uint8)]
class Flags2(Union):
# Union to set the In_Value flips the appropriate bits flags
# in_value can also be used to get the value of all set flags
_fields_ = [('bit', FlagBits2),
('in_value', c_uint8)]
class SetFlags():
# Class to handle Bit Flags for Message Attributes
field = None
field2 = None
def __init__(self, field, field2):
# get flags from message header
"""
:rtype : None
"""
self.field = field
self.field2 = field2
self.set_flags()
def set_flags(self):
attributes = Flags()
attributes.in_value = self.field
attributes2 = Flags2()
attributes2.in_value = self.field2
# Fido Message Header Structure
_struct_message_header_fields = [
# Structure Size 14
('H', 'message_type'),
('H', 'origin_node'),
('H', 'destination_node'),
('H', 'origin_network'),
('H', 'destination_network'),
('B', 'attributes_flags1'),
('B', 'attributes_flags2'),
('H', 'cost'),
]
_struct_fidonet_message_header = '<{0}'.format(
''.join(struct_val for struct_val, _ in _struct_message_header_fields))
FidonetMessageHeader = collections.namedtuple(
'FidonetMessageHeader', [field_name for _, field_name in _struct_message_header_fields])
def read_cstring(file_object, offset):
# Function to read text up to null terminator
new_string = ""
# jump to offset.
assert isinstance(offset, object)
file_object.seek(offset)
while True:
# read the file object
byte = file_object.read(1)
if not byte:
break
if byte in '\x00':
# Break on Null Terminated
break
new_string += str(byte)
return new_string
def read_message_text(file_object, offset):
# Function to read message text up to null terminator
assert isinstance(offset, object)
file_object.seek(offset)
message_string = ""
for chunk in iter(lambda: file_object.read(1), ''):
if chunk in '\x00':
break
message_string += chunk
return message_string
def track_area(area):
"""
:rtype : None
"""
if area_count[area] is not None:
area_count[area] += 1
else:
area_count[area] = 1
def print_area_count():
# Print out Counts of messages per area
print ''
total_messages = 0
total_areas = 0
for area in area_count:
print u'Area: {0} -> Total Messages: {1}'.format(
area, area_count[area])
total_messages += area_count[area]
total_areas += 1
# hard coded for now, this will be setup with dupe checking
total_messages_imported = total_messages
print ''
print 'Areas: {0} -> Messages: {1} -> Imported -> {2}.'.format(
total_areas, total_messages, total_messages_imported)
class StoredFidoInfo(object):
# Holds Fido Specific Message and Kludge Data That
# is Absent from the standard message layout
def __init__(self, index):
self.idx = index
self.__status = None
self.__date_processed = None
self.__kludge = set()
def status(self, flag):
self.__status = flag
def kludge_lines(self, k_lines):
assert isinstance(k_lines, object)
self.__kludge = k_lines
@property
def check_status(self):
return self.__status
@property
def check_kludge(self):
return self.__kludge
def save(self):
# persist message index record to database
from x84.bbs import DBProxy
new = self.idx is None
with DBProxy(FIDO_DB, use_session=False) as db_index:
# Not Used, Messages are saved first, with Fido
# Data save with matching index.
if new:
self.idx = max(map(int, db_index.keys()) or [-1]) + 1
db_index['%d' % (self.idx,)] = self
class Message(object):
# Message Object that will be pasted into.
def __init__(self):
"""
:rtype : None
:type self: str
"""
self.date_time = None
self.user_to = None
self.user_from = None
self.subject = None
self.area = None
self.tag_line = None
self.origin_line = None
self.kludge_lines = collections.OrderedDict()
self.seen_by = []
self.raw_data = None
self.message_header = None
self.packet_header = None
self.packet_address = None
self.network = None
# Clean Message Text, Split with CR, remove any LF!
self.message_lines = None
def import_messages(self):
from x84.bbs.msgbase import Msg
# hook into x84 and write message to default database and
# keep separate database for fido specific fields.
# 'author': msg.author,
# 'subject': msg.subject,
# 'recipient': msg.recipient,
# 'parent': parent,
# 'tags': [tag for tag in msg.tags if tag != network['name']],
# 'ctime': to_utctime(msg.ctime)
store_msg = Msg()
store_msg.recipient = unicode(self.user_to, 'CP437')
store_msg.author = unicode(self.user_from, 'CP437')
store_msg.subject = unicode(self.subject, 'CP437')
# Add Check here for Private Netmail messages, this functionality will be added lateron
# Convert from CP437 for high ascii, later on read CHRS kludge for origin character set
store_msg.body = unicode('\r'.join(self.message_lines).replace('\x9d', ''), 'CP437')
# If area is a normal public echo, default is public
store_msg.tags.add(u''.join('public'))
# Change to Network Name ie Agoranet
store_msg.tags.add(u''.join(self.network))
# Translate the area to the tag description.
# eg.. AGN_GEN -> general
area_tag = cfg.get_tag(self.network, self.area)
# print 'Area Tag: ' + area_tag
if area_tag is not None:
store_msg.tags.add(u''.join(area_tag))
# In testing
# if area is not a public echo, add to sysop group tag
# store_msg.tags.add(u''.join('sysop'))
# Convert Packet String to Date Time format.
# We should also get and check UTZ kludge line! Lateron for offset / Timezone.
# 26 Feb 15 18:04:00
date_object = datetime.datetime.strptime(self.date_time, '%d %b %y %H:%M:%S')
# do not save this message to network, we already received
# it from the network, set send_net=False
# Also avoid sending over X84 NET
store_msg.save(send_net=False, ctime=date_object)
print 'Msg Index after save: {0}'.format(store_msg.idx)
# Setup and store the fido kludge data
fido_msg = StoredFidoInfo(store_msg.idx)
fido_msg.status('received')
fido_msg.kludge_lines(self.kludge_lines)
fido_msg.save()
print 'Fido Index after save: {0}'.format(fido_msg.idx)
# get message index
# print 'Msg Index after save: {0}'.format(store_msg.idx)
# del store_msg
def add_kludge(self, line):
# Separates Kludge Lines into An Array of Fields
key, value = line.split(None, 1)
key = key[1:]
if key in self.kludge_lines:
assert isinstance(value, object)
self.kludge_lines[key].append(value)
else:
self.kludge_lines[key] = [value]
def parse_lines(self):
# Breaks up the message data into fields
stage = 1
message_body = []
# Setup Message Lines by breaking up raw data
self.message_lines = [x.strip('\n') for x in self.raw_data.split('\r')]
for line in self.message_lines:
if len(line) == 0:
# Empty Lines are Newlines
message_body.append('')
elif stage == 1:
# Start and Middle of Message Text
if line.startswith('AREA:'):
# grab description config file and translate area name
self.area = line.split(':')[1].lower()
# print 'Area : ' + self.area
# Add count for area
track_area(self.area)
elif line.startswith('\x01'):
self.add_kludge(line.strip())
elif line.startswith('--- '):
# Tracking Tag Lines might be a little much!
self.tag_line = line
# Leave Tag Line in message text
message_body.append(line)
elif 'Origin:' in line[2:10]:
# note some systems like Synchronet doesn't use * for origin prefix!!
# need to put range in for this!! +2, 10
self.origin_line = line
# Leave Tag Line in message text
message_body.append(line)
stage = 2
# not official, just preference to remove this invalid data record.
elif line.startswith('\x1ASAUCE00'):
# skip bad characters or records in messages
continue
elif line.endswith('\x04'):
# Skip SAUCE record end lines!, shouldn't be posted.
# bad characters
continue
else:
message_body.append(line)
elif stage == 2:
# Stage 2 After Origin Line Only
if line.startswith('\x01'):
self.add_kludge(line)
elif line.startswith('SEEN-BY:'):
self.seen_by.append(line)
else:
raise ValueError('Unexpected: %s' % line)
self.message_lines = message_body
# Import messages to x84
self.import_messages()
def __str__(self):
# Check this, should swap \r ? -MF
"""
:rtype : str
"""
return '\n'.join(self.message_lines)
def serialize(self):
# Build The Message for Writing out to Packet
lines = []
if self.area:
lines.append('AREA:%s' % self.area)
# Setup Kludge Lines
for key, kludge_value in self.kludge_lines.items():
for value in kludge_value:
# Check if these needs \r at end of line!!
lines.append('\x01{key} {val}'.format(key=key, val=value))
lines.extend(self.message_lines)
if self.origin_line:
lines.append(self.origin_line)
lines.extend(self.seen_by)
class ParsePackets(object):
area_count_dict = {}
def __init__(self, packet_processing):
# Inbound or Outbound processing.
"""
:type packet_processing: str
"""
_packet_processing = packet_processing
if _packet_processing in 'read':
process_inbound()
print_area_count()
elif _packet_processing in 'write':
process_outbound()
def process_outbound():
# Scan for New Messages ready for sending out
"""
:rtype : none
"""
from x84.bbs import DBProxy
print 'process_outbound()'
# Status is a list of all Message Keys
status = set(int(key) for key in DBProxy(FIDO_DB).keys())
print status
# Scan message Status.
with DBProxy(FIDO_DB) as fido_db:
for key, values in fido_db.items():
# print key, values.check_status
# print key, values.check_kludge
for k, v in values.check_kludge.items():
# Grabs Key values of all Kludges
print k, v
# Work out kludge lines now.
# Example modern msg id.
'''
TID: ['Mystic BBS 1.10', FastEcho, SBBSecho, MBSE-FIDO]
PID: ['SMBUTIL', MBSE-FIDO]
MSGID: ['18386.agn_l46@46:1/100 1955835b']
REPLY: ['46:1/145 4659a1ce']
TZUTC: ['-0600']
PATH: ['1/100']
CHRS: ['CP437 2']
'''
def process_inbound():
# Process all packets waiting in the inbound_folder
"""
:rtype : none
"""
message_count = 0
for file_path_zip in glob.glob(os.path.join(cfg.inbound_folder, u'*.*')):
# Uncompress packet bundles, then loop to read packet/message headers/messages
try:
# unzip a clean bundle
with zipfile.ZipFile(file_path_zip) as zip_obj:
print u'Uncompress Bundle: ' + os.path.basename(file_path_zip)
zip_obj.extractall(cfg.unpack_folder)
# Loop and process all packets
for file_name in os.listdir(cfg.unpack_folder):
# Parse Each Packet for the Header first.
print u'Parsing Mail Packet: ' + file_name
# Open then Parse Each Packet
fido_object = open(os.path.join(cfg.unpack_folder, file_name), 'rb')
try:
# make Sure we don't read past the end of the file!
packet_header_read = fido_object.read()[:58]
except EOFError:
# move to next packet if were at the end.
break
if not packet_header_read:
# move to next packet, log error here
print u'Error: unable to read packet header: ' + file_name
break
# Make sure we have correct size! Otherwise were done.
# print 'packet_header_read len: ' + str(len(packet_header_read))
if len(packet_header_read) < 58:
# End of File can have (2) Bytes, catch this.
break
# Read the Packet Header
fido_header = FidonetPacketHeader(
*struct.unpack(_struct_fidonet_packet, packet_header_read))
# Test the packet header
if fido_header.packet_type != 2:
print u'Error: fido packet not Type-2: ' + file_name
break
# Validate packet is addressed to this system
# Add 5D addresses? have @domain like @agoranet
if fido_header.destination_point != 0:
# 4D address
packet_address = '{zone}:{net}/{node}.{point}'.format(
zone=fido_header.destination_zone, net=fido_header.destination_network,
node=fido_header.destination_node, point=fido_header.destination_point)
else:
# 3D Address no point.
packet_address = '{zone}:{net}/{node}'.format(
zone=fido_header.destination_zone, net=fido_header.destination_network,
node=fido_header.destination_node)
# If Address is not in our network, skip to next packet.
current_network = cfg.check_network_address(packet_address)
if current_network is None:
print u'Error: packet not addressed to your node: {packet}, '\
.format(packet=packet_address)
break
print u'Packet Received for: {network} -> {packet}'\
.format(network=current_network, packet=packet_address)
assert isinstance(fido_header, object)
# print fido_header
offset = struct.calcsize(_struct_fidonet_packet)
message_count = 0
while True:
# Reset Position to right after Fido Header
fido_object.seek(offset)
# Try to parse the message header
try:
# make Sure we don't read past the end of the file!
message_header_read = fido_object.read()[:14]
except EOFError:
# move to next packet if were at the end.
break
if not message_header_read:
# move to next packet, log error here
break
# Make sure we have correct size! Otherwise were done.
# print 'message_header_read len: ' + str(len(message_header_read))
if len(message_header_read) <= 2:
# End of File can have (2) Bytes, catch this.
break
elif len(message_header_read) < 14:
# Read was short!
print u'Error: unable to read message header: ' + file_name
break
# Read the Message Header
fido_message_header = FidonetMessageHeader(
*struct.unpack(_struct_fidonet_message_header, message_header_read))
assert isinstance(fido_message_header, object)
SetFlags(fido_message_header.attributes_flags1,
fido_message_header.attributes_flags2)
# Update The Offset
offset += struct.calcsize(_struct_fidonet_message_header)
# Next move back to the next position
""" Next we need to parse For '\x00' terminated strings.
('20s', 'dateTime'),
('36s', 'toUsername'),
('36s', 'fromUsername'),
('72s', 'subject')
"""
# Use cleaner way to keep track of offset!!
date_time_string = read_cstring(fido_object, offset)
offset += len(date_time_string) + 1
username_to = read_cstring(fido_object, offset)
offset += len(username_to) + 1
username_from = read_cstring(fido_object, offset)
offset += len(username_from) + 1
subject_string = read_cstring(fido_object, offset)
offset += len(subject_string) + 1
# We now read the entire message up to null terminator
message_string = read_message_text(fido_object, offset)
offset += len(message_string) + 1
# Breaks up the message and separates out kludge lines from text.
# print Message(message_string, username_to, username_from, subject_string)
current_message = Message()
current_message.date_time = date_time_string
current_message.user_to = username_to
current_message.user_from = username_from
current_message.subject = subject_string
current_message.raw_data = message_string
# Packet Headers will check for source / destination address
# mainly dupe checking
current_message.packet_header = fido_header
# Message Headers will be checked for Import/Export flags etc.
current_message.message_header = fido_message_header
# Populated the Current Network and Address.
current_message.network = current_network
current_message.packet_address = packet_address
# First Parse the Raw Data into Message Lines and
# break out Kludge lines from text
# if No errors then Import Message to x84
current_message.parse_lines()
message_count += 1
# Cleanup
# del current_message
# Cleanup for next run
fido_object.close()
print u' Messages This Packet -> ' + str(message_count)
print '*' * 30
finally:
# Clear the unpack_folder here later on, leave for testing, just overwrites!
print u'End of Bundle'
print '*' * 60
# Clear out any packets before running next bundle
clear_files = glob.glob(os.path.join(cfg.unpack_folder, u'*.*'))
for file in clear_files:
os.remove(file)
class TossMessages(ParsePackets):
# handle incoming messages
def __init__(self):
# Inbound or Outbound processing.
"""
:rtype : none
"""
_packet_processing = 'read'
super(TossMessages, self).__init__(_packet_processing)
class ScanMessages(ParsePackets):
# handle outgoing messages
def __init__(self):
# Inbound or Outbound processing.
"""
:rtype : none
"""
_packet_processing = 'write'
super(ScanMessages, self).__init__(_packet_processing)
def main(background_daemon=False):
# Scan for Incoming Message and Import them
if not background_daemon:
# Import Message 80% Done.
# TossMessages()
# Export Messages WIP!
ScanMessages()
if __name__ == '__main__':
# do not execute message polling as a background thread.
main(background_daemon=False)