forked from crustymonkey/python-libmilter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libmilter.py
executable file
·1503 lines (1359 loc) · 47 KB
/
libmilter.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/python
# This file is part of python-libmilter.
#
# python-libmilter 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 3 of the License, or
# (at your option) any later version.
#
# python-libmilter 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 python-libmilter. If not, see <http://www.gnu.org/licenses/>.
import struct , sys , select , threading , socket , time , os , signal
# Turn debugging on or off
DEBUG = 0
if DEBUG:
import traceback
__version__ = '1.0.3'
#
# Standard Sendmail Constants
#
# These are flags stating what, we, the client will want to do (SMFIF_*) {{{
SMFIF_ADDHDRS = 0x01 # We may add headers
SMFIF_CHGBODY = 0x02 # We may replace body
SMFIF_ADDRCPT = 0x04 # We may add recipients
SMFIF_DELRCPT = 0x08 # We may delete recipients
SMFIF_CHGHDRS = 0x10 # We may change/delete headers
SMFIF_QUARANTINE = 0x20 # We may quarantine envelope
# End version 2
SMFIF_CHGFROM = 0x40 # We may replace the sender
SMFIF_ADDRCPT_PAR = 0x80 # We may add recipients + args
SMFIF_SETSYMLIST = 0x100 # We may send macro names CURRENTLY UNSUPPORTED
SMFIF_ALLOPTS_V2 = SMFIF_ADDHDRS | SMFIF_CHGBODY | SMFIF_ADDRCPT | \
SMFIF_DELRCPT | SMFIF_CHGHDRS | SMFIF_QUARANTINE
SMFIF_ALLOPTS_V6 = SMFIF_CHGFROM | SMFIF_ADDRCPT_PAR | SMFIF_SETSYMLIST
SMFIF_ALLOPTS = SMFIF_ALLOPTS_V2 | SMFIF_ALLOPTS_V6
SMFIF_OPTS = {
SMFIF_ADDHDRS: 'addhdrs' ,
SMFIF_CHGBODY: 'chgbody' ,
SMFIF_ADDRCPT: 'addrcpt' ,
SMFIF_DELRCPT: 'delrcpt' ,
SMFIF_CHGHDRS: 'chghdrs' ,
SMFIF_QUARANTINE: 'quarantine' ,
SMFIF_CHGFROM: 'chgfrom' ,
SMFIF_ADDRCPT_PAR: 'addrcpt_wargs' ,
SMFIF_SETSYMLIST: 'setsymlist' ,
}
# }}}
# These are mainly flags to be sent during option negotiation (SMFIP_*) {{{
SMFIP_NOCONNECT = 0x01 # We don't want connect info
SMFIP_NOHELO = 0x02 # We don't want HELO info
SMFIP_NOMAIL = 0x04 # We don't want MAIL info
SMFIP_NORCPT = 0x08 # We don't want RCPT info
SMFIP_NOBODY = 0x10 # We don't want the body
SMFIP_NOHDRS = 0x20 # We don't want the headers
SMFIP_NOEOH = 0x40 # We don't want the EOH
# End version 2
SMFIP_NR_HDR = 0x80 # We won't reply to the headers
SMFIP_NOHREPL = SMFIP_NR_HDR
SMFIP_NOUNKNOWN = 0x100 # We don't want any unknown cmds
SMFIP_NODATA = 0x200 # We don't want the DATA cmd
SMFIP_SKIP = 0x400 # MTA supports the SMFIS_SKIP
SMFIP_RCPT_REJ = 0x800 # We want rejected RCPTs
SMFIP_NR_CONN = 0x1000 # We don't reply to connect info
SMFIP_NR_HELO = 0x2000 # We don't reply to HELO info
SMFIP_NR_MAIL = 0x4000 # We don't reply to MAIL info
SMFIP_NR_RCPT = 0x8000 # We don't reply to RCPT info
SMFIP_NR_DATA = 0x10000 # We don't reply to DATA info
SMFIP_NR_UNKN = 0x20000 # We don't reply to UNKNOWN
SMFIP_NR_EOH = 0x40000 # We don't reply to eoh
SMFIP_NR_BODY = 0x80000 # We don't reply for a body chunk
SMFIP_HDR_LEADSPC = 0x100000 # header value has leading space
# All protos
SMFIP_ALLPROTOS_V2 = SMFIP_NOCONNECT | SMFIP_NOHELO | SMFIP_NOMAIL | \
SMFIP_NORCPT | SMFIP_NOBODY | SMFIP_NOHDRS | SMFIP_NOEOH
SMFIP_ALLPROTOS_V6 = SMFIP_NR_HDR | SMFIP_NOUNKNOWN | SMFIP_NODATA | \
SMFIP_SKIP | SMFIP_RCPT_REJ | SMFIP_NR_CONN | SMFIP_NR_HELO | \
SMFIP_NR_MAIL | SMFIP_NR_RCPT | SMFIP_NR_DATA | SMFIP_NR_UNKN | \
SMFIP_NR_EOH | SMFIP_NR_BODY | SMFIP_HDR_LEADSPC
SMFIP_ALLPROTOS = SMFIP_ALLPROTOS_V2 | SMFIP_ALLPROTOS_V6
SMFIP_PROTOS = {
SMFIP_NOCONNECT: 'noconnect',
SMFIP_NOHELO: 'nohelo' ,
SMFIP_NOMAIL: 'nomail' ,
SMFIP_NORCPT: 'norcpt' ,
SMFIP_NOBODY: 'nobody' ,
SMFIP_NOHDRS: 'nohdrs' ,
SMFIP_NOEOH: 'noeoh' ,
SMFIP_NOUNKNOWN: 'nounknown' ,
SMFIP_NODATA: 'nodata' ,
SMFIP_SKIP: 'skip' ,
SMFIP_RCPT_REJ: 'wantrej' ,
SMFIP_NR_HDR: 'noreplhdr' ,
SMFIP_NR_CONN: 'noreplconn' ,
SMFIP_NR_HELO: 'noreplhelo' ,
SMFIP_NR_MAIL: 'noreplmail' ,
SMFIP_NR_RCPT: 'noreplrcpt' ,
SMFIP_NR_DATA: 'norepldata' ,
SMFIP_NR_UNKN: 'noreplunkn' ,
SMFIP_NR_EOH: 'norepleoh' ,
SMFIP_NR_BODY: 'noreplbody' ,
SMFIP_HDR_LEADSPC: 'hdrleadspc' ,
}
# }}}
# Network protocol families (SMFIA_*) {{{
SMFIA_UNKNOWN = 'U' # Unknown
SMFIA_UNIX = 'L' # Unix/local
SMFIA_INET = '4' # inet - ipv4
SMFIA_INET6 = '6' # inet6 - ipv6
# }}}
# Macros sent from the MTA (SMFIC_*) {{{
SMFIC_ABORT = 'A' # Abort
SMFIC_BODY = 'B' # Body chunk
SMFIC_CONNECT = 'C' # Connection info
SMFIC_MACRO = 'D' # Define macro
SMFIC_BODYEOB = 'E' # Final body chunk
SMFIC_HELO = 'H' # HELO
SMFIC_HEADER = 'L' # Header
SMFIC_MAIL = 'M' # MAIL from
SMFIC_EOH = 'N' # eoh
SMFIC_OPTNEG = 'O' # Option negotiation
SMFIC_QUIT = 'Q' # QUIT
SMFIC_RCPT = 'R' # RCPT to
# End Version 2
SMFIC_DATA = 'T' # DATA
SMFIC_UNKNOWN = 'U' # Any unknown command
SMFIC_QUIT_NC = 'K' # Quit + new connection
# My shortcut for body related macros
SMFIC_BODY_MACS = (SMFIC_DATA , SMFIC_HEADER , SMFIC_EOH , SMFIC_BODY)
# }}}
# Responses/commands that we send to the MTA (SMFIR_*) {{{
SMFIR_ADDRCPT = '+' # Add recipient
SMFIR_DELRCPT = '-' # Remove recipient
SMFIR_ACCEPT = 'a' # Accept
SMFIR_REPLBODY = 'b' # Replace body (chunk)
SMFIR_CONTINUE = 'c' # Continue
SMFIR_DISCARD = 'd' # Discard
SMFIR_ADDHEADER = 'h' # Add header
SMFIR_CHGHEADER = 'm' # Change header
SMFIR_PROGRESS = 'p' # Progress
SMFIR_QUARANTINE = 'q' # Quarantine
SMFIR_REJECT = 'r' # Reject
SMFIR_TEMPFAIL = 't' # Tempfail
SMFIR_REPLYCODE = 'y' # For setting the reply code
# End Version 2
SMFIR_CONN_FAIL = 'f' # Cause a connection failure
SMFIR_SHUTDOWN = '4' # 421: shutdown (internal to MTA)
SMFIR_INSHEADER = 'i' # Insert header
SMFIR_SKIP = 's' # Skip further events of this type
SMFIR_CHGFROM = 'e' # Change sender (incl. ESMTP args)
SMFIR_ADDRCPT_PAR = '2' # Add recipient (incl. ESMTP args)
SMFIR_SETSYMLIST = 'l' # Set list of symbols
# }}}
# Macro Class Numbers {{{
#
# Version 6 only
# Macro class numbers, to identify the optional macro name lists that
# may be sent after the initial negotiation header
SMFIM_CONNECT = 0 # Macros for connect
SMFIM_HELO = 1 # Macros for HELO
SMFIM_ENVFROM = 2 # Macros for MAIL from
SMFIM_ENVRCPT = 3 # Macros for RCPT to
SMFIM_DATA = 4 # Macros for DATA
SMFIM_EOM = 5 # Macros for end of message
SMFIM_EOH = 6 # Macros for end of header
# }}}
MILTER_CHUNK_SIZE = 65536
# My Constants -- tables and helpers {{{
# Optional callbacks
optCBs = {
'connect': (SMFIP_NOCONNECT , SMFIP_NR_CONN) ,
'helo': (SMFIP_NOHELO , SMFIP_NR_HELO) ,
'mailFrom': (SMFIP_NOMAIL , SMFIP_NR_MAIL) ,
'rcpt': (SMFIP_NORCPT , SMFIP_NR_RCPT) ,
'header': (SMFIP_NOHDRS , SMFIP_NR_HDR) ,
'eoh': (SMFIP_NOEOH , SMFIP_NR_EOH) ,
'data': (SMFIP_NODATA , SMFIP_NR_DATA) ,
'body': (SMFIP_NOBODY , SMFIP_NR_BODY) ,
'unknown': (SMFIP_NOUNKNOWN , SMFIP_NR_UNKN) ,
}
protoMap = {
SMFIC_CONNECT: 'connect' ,
SMFIC_HELO: 'helo' ,
SMFIC_MAIL: 'mailFrom' ,
SMFIC_RCPT: 'rcpt' ,
SMFIC_HEADER: 'header' ,
SMFIC_EOH: 'eoh' ,
SMFIC_DATA: 'data' ,
SMFIC_BODY: 'body' ,
SMFIC_UNKNOWN: 'unknown' ,
}
# Milter version global for use by the decorators during init
_milterVersion = 2
# }}}
# The register for deferreds
DEFERRED_REG = set()
#
# Exceptions {{{
#
class InvalidPacket(Exception):
def __init__(self , partialPacket , cmds , *args , **kwargs):
Exception.__init__(self , *args , **kwargs)
self.pp = partialPacket
self.partialPacket = self.pp
self.cmds = cmds
class UnsupportedError(Exception):
pass
class UnknownError(Exception):
pass
class RequiredCallbackError(Exception):
pass
# }}}
#
# Deferreds {{{
#
class Deferred(object):
pass
class DeferToThread(Deferred):
def __init__(self , cb , *args , **kwargs):
global DEFERRED_REG
self.result = None
self.completed = False
self.error = None
self.callbacks = []
self.errbacks = []
t = threading.Thread(target=self._wrapper , args=(cb , args , kwargs))
t.daemon = True
t.start()
DEFERRED_REG.add(self)
def _wrapper(self , cb , args , kwargs):
try:
self.result = cb(*args , **kwargs)
except Exception , e:
self.error = e
self.completed = True
def addCallback(self , cb , *args , **kwargs):
self.callbacks.append((cb , args , kwargs))
def addErrback(self , eb , *args , **kwargs):
self.errbacks.append((eb , args , kwargs))
def callCallbacks(self):
if not self.completed: return
for cb , a , kw in self.callbacks:
cb(self.result , *a , **kw)
del self.callbacks
del self.errbacks
def callErrbacks(self):
if not self.completed: return
for cb , a , kw in self.errbacks:
cb(self.error , *a , **kw)
del self.callbacks
del self.errbacks
# }}}
#
# Utility functions {{{
#
idCounter = 0
def getId():
global idCounter
idCounter += 1
return idCounter
def pack_uint32(i):
return struct.pack('!I' , i)
def pack_uint16(i):
return struct.pack('!H' , i)
def unpack_uint32(s):
return struct.unpack('!I' , s)[0]
def unpack_uint16(s):
return struct.unpack('!H' , s)[0]
def parse_packet(p):
ret = []
remaining = 0
while p:
if len(p) < 4:
raise InvalidPacket(p , ret , 'The packet is too small to '
'contain any info (%d): %r' % (len(p) , p))
length = unpack_uint32(p[:4])
pend = length + 4
contents = p[4:pend]
if len(contents) < length:
remaining = length - len(contents)
ret.append(contents)
p = p[pend:]
return (ret , remaining)
def readUntilNull(s):
"""
Read a string until a null is encountered
returns (string up to null , remainder after null)
"""
item = s.split('\0' , 1)
if len(item) == 1:
return (item[0] , None)
else:
return (item[0] , item[1])
def checkData(data , macro):
if not data[0] == macro:
raise UnknownError('Command does not start with correct '
'MACRO: %s (%s) should be %s' % (data[0] , data , macro))
def dictFromCmd(cmd):
d = {}
while cmd and len(cmd) > 1:
key , rem = readUntilNull(cmd)
key = key.strip('{}')
if rem:
val , rem = readUntilNull(rem)
else:
val = None
d[key] = val
cmd = rem
return d
def debug(msg , level=1 , protId=0):
if not DEBUG: return
if level <= DEBUG:
out = '[%s] DEBUG: ' % time.strftime('%H:%M:%S')
if protId:
out += 'ID: %d ; ' % protId
out += msg
print >> sys.stderr , out
# }}}
# Response Constants {{{
#
# Constants for responses back to the MTA. You should use these actions
# at the end of each callback. If none of these are specified,
# CONTINUE is used as the default
#
ACCEPT = pack_uint32(1) + SMFIR_ACCEPT
CONTINUE = pack_uint32(1) + SMFIR_CONTINUE
REJECT = pack_uint32(1) + SMFIR_REJECT
TEMPFAIL = pack_uint32(1) + SMFIR_TEMPFAIL
DISCARD = pack_uint32(1) + SMFIR_DISCARD
CONN_FAIL = pack_uint32(1) + SMFIR_CONN_FAIL
SHUTDOWN = pack_uint32(1) + SMFIR_SHUTDOWN
# }}}
#
# Decorators {{{
#
def callInThread(f):
def newF(*args , **kwargs):
inst = args[0]
defrd = DeferToThread(f , *args , **kwargs)
defrd.addCallback(_onCITSuccess , inst)
defrd.addErrback(_onCITFail , inst)
return defrd
return newF
# callInThread success callback
def _onCITSuccess(res , inst):
if res:
inst.send(res)
# callInThread fail callback
def _onCITFail(fail , inst):
inst.log(str(fail))
# Use this decorator when the callback should not be sent from the MTA
def noCallback(f):
global _milterVersion
fname = f.__name__
if not fname in optCBs:
raise RequiredCallbackError('function %s is NOT an optional callback' %
fname)
def newF(*args , **kwargs):
pass
newF.protos = optCBs[fname][0]
return newF
# Use this decorator when the callback response is not necessary
def noReply(f):
global _milterVersion
fname = f.__name__
if not fname in optCBs:
raise RequiredCallbackError('function %s is NOT an optional callback' %
fname)
_milterVersion = 6
def newF(*args , **kwargs):
return f(*args , **kwargs)
newF.protos = optCBs[fname][1]
return newF
# }}}
# Dummy lock for use with a ThreadFactory
# class DummyLock {{{
class DummyLock(object):
def acquire(self):
return True
def release(self):
return True
#}}}
#
# Start implementation stuff
#
# class ThreadMixin {{{
class ThreadMixin(threading.Thread):
def run(self):
self._sockLock = DummyLock()
while True:
buf = ''
try:
buf = self.transport.recv(MILTER_CHUNK_SIZE)
except AttributeError:
# Socket has been closed
pass
except socket.error:
pass
except socket.timeout:
pass
if not buf:
try:
self.transport.close()
except:
pass
self.connectionLost()
break
try:
self.dataReceived(buf)
except Exception , e:
self.log('AN EXCEPTION OCCURED IN %s: %s' % (self.id , e))
if DEBUG:
traceback.print_exc()
debug('AN EXCEPTION OCCURED: %s' % e , 1 , self.id)
self.connectionLost()
break
# }}}
# class ForkMixin {{{
class ForkMixin(object):
def start(self):
# Fork and run
if not os.fork():
self.run()
os._exit(0)
else:
return
def run(self):
self._sockLock = DummyLock()
while True:
buf = ''
try:
buf = self.transport.recv(MILTER_CHUNK_SIZE)
except AttributeError:
# Socket has been closed
pass
except socket.error:
pass
except socket.timeout:
pass
if not buf:
try:
self.transport.close()
except:
pass
self.connectionLost()
break
try:
self.dataReceived(buf)
except Exception , e:
self.log('AN EXCEPTION OCCURED IN %s: %s' % (self.id , e))
if DEBUG:
traceback.print_exc()
debug('AN EXCEPTION OCCURED: %s' % e , 1 , self.id)
self.connectionLost()
break
#self.log('Exiting child process')
# }}}
# class MilterProtocol {{{
class MilterProtocol(object):
"""
A replacement for the C libmilter library, all done in pure Python.
Subclass this and implement the overridable callbacks.
"""
# Class vars and __init__() {{{
def __init__(self , opts=0 , protos=0):
"""
Initialize all the instance variables
"""
self.id = getId()
self.transport = None
self._opts = opts # Milter options (SMFIF_*)
self.milterVersion = _milterVersion # Default milter version
self.protos = protos # These are the SMFIP_* options
if self._opts & SMFIF_ALLOPTS_V6:
self.milterVersion = 6
for fname in optCBs:
f = getattr(self , fname)
p = getattr(f , 'protos' , 0)
self.protos |= p
self.closed = False
self._qid = None # The Queue ID assigned by the MTA
self._mtaVersion = 0
self._mtaOpts = 0
self._mtaProtos = 0
self._sockLock = threading.Lock()
# The next 4 vars are temporary state buffers for the 3 ways
# a packet can be split
self._partial = None
self._partialHeader = None
self._lastMacro = None
self._MACMAP = {
SMFIC_CONNECT: self._connect ,
SMFIC_HELO: self._helo ,
SMFIC_MAIL: self._mailFrom ,
SMFIC_RCPT: self._rcpt ,
SMFIC_HEADER: self._header ,
SMFIC_EOH: self._eoh ,
SMFIC_DATA: self._data ,
SMFIC_BODY: self._body ,
SMFIC_BODYEOB: self._eob ,
SMFIC_ABORT: self._abort ,
SMFIC_QUIT: self._close ,
SMFIC_UNKNOWN: self._unknown ,
}
# }}}
#
# Twisted method implementations {{{
#
def connectionLost(self , reason=None):
"""
The connection is lost, so we call the close method if it hasn't
already been called
"""
self._close()
def dataReceived(self , buf):
"""
This is the raw data receiver that calls the appropriate
callbacks based on what is received from the MTA
"""
remaining = 0
cmds = []
pheader = ''
debug('raw buf: %r' % buf , 4 , self.id)
if self._partialHeader:
pheader = self._partialHeader
debug('Working a partial header: %r ; cmds: %r' % (pheader , cmds) ,
4 , self.id)
buf = pheader + buf
self._partialHeader = None
if self._partial:
remaining , pcmds = self._partial
self._partial = None
buflen = len(buf)
pcmds[-1] += buf[:remaining]
buf = buf[remaining:]
cmds.extend(pcmds)
debug('Got a chunk of a partial: len: %d ; ' % buflen +
'end of prev buf: %r ; ' % cmds[-1][-10:] +
'start of new buf: %r ; ' % buf[:10] +
'qid: %s ; ' % self._qid , 4 , self.id)
if buflen < remaining:
remaining -= buflen
self._partial = (remaining , cmds)
return
remaining = 0
if buf:
curcmds = []
try:
curcmds , remaining = parse_packet(buf)
except InvalidPacket , e:
debug('Found a partial header: %r; cmdlen: %d ; buf: %r' %
(e.pp , len(e.cmds) , buf) , 2 , self.id)
cmds.extend(e.cmds)
self._partialHeader = e.pp
else:
cmds.extend(curcmds)
debug('parsed packet, %d cmds , %d remaining: cmds: %r ; qid: %s' %
(len(cmds) , remaining , cmds , self._qid) , 2 , self.id)
if remaining:
self._partial = (remaining , cmds[-1:])
cmds = cmds[:-1]
if cmds:
self._procCmdAndData(cmds)
# }}}
#
# Utility functions {{{
#
def _procCmdAndData(self , cmds):
skipNum = 0
toSend = ''
for i , cmd in enumerate(cmds):
toSend = ''
mtype = ''
firstLet = cmd[0]
if skipNum:
skipNum -= 1
continue
elif firstLet == SMFIC_OPTNEG:
debug('MTA OPTS: %r' % cmd , 4 , self.id)
toSend = self._negotiate(cmd)
elif firstLet == SMFIC_ABORT:
self._abort()
continue
elif firstLet == SMFIC_QUIT or \
firstLet == SMFIC_QUIT_NC:
self._close()
continue
elif firstLet == SMFIC_MACRO:
# We have a command macro. We just store for when the
# command comes back up
self._lastMacro = cmd
continue
elif firstLet in self._MACMAP:
mtype = cmd[0]
if toSend and not mtype:
# Basically, we just want to send something back
pass
elif mtype not in self._MACMAP:
raise UnsupportedError('Unsupported MACRO in '
'%d: %s (%s)' % (self.id , mtype , cmd))
else:
lmtype = None
if self._lastMacro is not None and len(self._lastMacro) > 1:
lmtype = self._lastMacro[1:2]
d = [cmd]
macro = None
if lmtype == mtype:
macro = self._lastMacro
if mtype in protoMap:
nc = optCBs[protoMap[mtype]][0]
nr = optCBs[protoMap[mtype]][1]
if self.protos & nc:
debug('No callback set for %r' % self._MACMAP[mtype] ,
4 , self.id)
# There is a nocallback set for this, just continue
continue
elif self.protos & nr:
# No reply for this, just run it and discard
# the response
debug('No response set for %r' % self._MACMAP[mtype] ,
4 , self.id)
self._MACMAP[mtype](macro , d)
continue
# Run it and send back to the MTA
debug('Calling %r for qid: %s' % (self._MACMAP[mtype] ,
self._qid) , 4 , self.id)
toSend = self._MACMAP[mtype](macro , d)
if not toSend:
# If there was not a return value and we get here, toSend
# should be set to CONTINUE
toSend = CONTINUE
if toSend and not isinstance(toSend , Deferred):
self.send(toSend)
def _getOptnegPkt(self):
"""
This is a simple convenience function to create an optneg
packet -- DO NOT OVERRIDE UNLESS YOU KNOW WHAT YOU ARE DOING!!
"""
self._opts = self._opts & self._mtaOpts
self.protos = self.protos & self._mtaProtos
s = SMFIC_OPTNEG + pack_uint32(self._mtaVersion) + \
pack_uint32(self._opts) + pack_uint32(self.protos)
s = pack_uint32(len(s)) + s
return s
def log(self , msg):
"""
Override this in a subclass to display messages
"""
pass
def send(self , msg):
"""
A simple wrapper for self.transport.sendall
"""
self._sockLock.acquire()
try:
debug('Sending: %r' % msg , 4 , self.id)
self.transport.sendall(msg)
except AttributeError , e:
emsg = 'AttributeError sending %s: %s' % (msg , e)
self.log(emsg)
debug(emsg)
except socket.error , e:
emsg = 'Socket Error sending %s: %s' % (msg , e)
self.log(emsg)
debug(emsg)
self._sockLock.release()
# }}}
#
# Raw data callbacks {{{
# DO NOT OVERRIDE THESE UNLESS YOU KNOW WHAT YOU ARE DOING!!
#
def _negotiate(self , cmd):
"""
Handles the opening optneg packet from the MTA
"""
cmd = cmd[1:]
v , mtaOpts , mtaProtos = struct.unpack('!III' , cmd)
self._mtaVersion = v
self._mtaOpts = mtaOpts
self._mtaProtos = mtaProtos
return self._getOptnegPkt()
def _connect(self , cmd , data):
"""
Parses the connect info from the MTA, calling the connect()
method with (<reverse hostname> , <ip family> , <ip addr> ,
<port> , <cmdDict>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
data = data[0]
hostname = ''
family = ''
port = -1
ip = ''
if data:
checkData(data , SMFIC_CONNECT)
hostname , rem = readUntilNull(data[1:])
family = rem[0]
if family != SMFIA_UNKNOWN:
port = unpack_uint16(rem[1:3])
ip = rem[3:-1]
return self.connect(hostname , family , ip , port , md)
def _helo(self , cmd , data):
"""
Parses the helo info from the MTA and calls helo() with
(<helo name>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
data = data[0]
heloname = ''
if data:
checkData(data , SMFIC_HELO)
heloname = data[1:-1]
return self.helo(heloname)
def _mailFrom(self , cmd , data):
"""
Parses the MAIL FROM info from the MTA and calls mailFrom()
with (<from addr> , <cmdDict>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
data = data[0]
mfrom = ''
if data:
mfrom = data[1:-1]
# Return the mail from address parsed by the MTA, if possible
if md.has_key('mail_addr'):
mfrom = md['mail_addr']
if md.has_key('i'):
self._qid = md['i']
return self.mailFrom(mfrom , md)
def _rcpt(self , cmd , data):
"""
Parses the RCPT TO info from the MTA and calls rcpt()
with (<rcpt addr> , <cmdDict>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
data = data[0]
rcpt = ''
if data:
rcpt = data[1:-1]
elif md.has_key('rcpt_addr'):
rcpt = md['rcpt_addr']
if md.has_key('i'):
self._qid = md['i']
return self.rcpt(rcpt , md)
def _header(self , cmd , data):
"""
Parses the header from the MTA and calls header() with
(<header name> , <header value> , <cmdDict>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
data = data[0]
key = ''
val = ''
if md.has_key('i'):
self._qid = md['i']
if data:
key , rem = readUntilNull(data[1:])
val , rem = readUntilNull(rem)
if rem:
raise UnknownError('Extra data for header: %s=%s (%s)' % (key ,
val , data))
return self.header(key , val , md)
def _eoh(self , cmd , data):
"""
Parses the End Of Header from the MTA and calls eoh() with
(<cmdDict>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
if md.has_key('i'):
self._qid = md['i']
return self.eoh(md)
def _data(self , cmd , data):
"""
Parses the DATA call from the MTA and calls data() with (<cmdDict>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
if md.has_key('i'):
self._qid = md['i']
return self.data(md)
def _body(self , cmd , data):
"""
Parses the body chunk from the MTA and calls body() with
(<body chunk> , <cmdDict>)
"""
data = data[0]
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
chunk = ''
if md.has_key('i'):
self._qid = md['i']
if data:
chunk = data[1:]
return self.body(chunk , md)
def _eob(self , cmd , data):
"""
Parses the End Of Body from the MTA and calls eob() with
(<cmdDict>)
"""
md = {}
if cmd is not None:
md = dictFromCmd(cmd[2:])
if md.has_key('i'):
self._qid = md['i']
ret = self.eob(md)
return ret
def _close(self , cmd=None , data=None):
"""
This is a wrapper for close() that checks to see if close()
has already been called and calls it if it has not. This
will also close the transport's connection.
"""
if not self.closed:
self.closed = True
self.transport = None
self.close()
def _abort(self):
"""
This is called when an ABORT is received from the MTA. It
calls abort() and then _close()
"""
self._qid = None
self.abort()
def _unknown(self , cmd , data):
"""
Unknown command sent. Call unknown() with (<cmdDict> , <data>)
"""
if cmd is not None:
md = dictFromCmd(cmd[2:])
md = dictFromCmd(cmd[2:])
return self.unknown(md , data)
# }}}
#
# Message modification methods {{{
# NOTE: These can ONLY be called from eob()
#
def addRcpt(self , rcpt , esmtpAdd=''):
"""
This will tell the MTA to add a recipient to the email
NOTE: This can ONLY be called in eob()
"""
if esmtpAdd:
if not SMFIF_ADDRCPT_PAR & self._opts & self._mtaopts:
print 'Add recipient par called without the proper opts set'
return
req = '%s%s\0%s\0' % (SMFIR_ADDRCPT_PAR , rcpt , esmtpAdd)
req = pack_uint32(len(req)) + req
else:
if not SMFIF_ADDRCPT & self._opts & self._mtaOpts:
print 'Add recipient called without the proper opts set'
return
req = '%s%s\0' % (SMFIR_ADDRCPT , rcpt)
req = pack_uint32(len(req)) + req
self.send(req)
def delRcpt(self , rcpt):
"""
This will tell the MTA to delete a recipient from the email
NOTE: This can ONLY be called in eob()
NOTE: The recipient address must be EXACTLY the same as one
of the addresses received in the rcpt() callback'
"""
if not SMFIF_DELRCPT & self._opts & self._mtaOpts:
print 'Delete recipient called without the proper opts set'
return
req = '%s%s\0' % (SMFIR_DELRCPT , rcpt)
req = pack_uint32(len(req)) + req
self.send(req)
def replBody(self , body):
"""
This will replace the body of the email with a new body
NOTE: This can ONLY be called in eob()
"""
if not SMFIF_CHGBODY & self._opts & self._mtaOpts:
print 'Tried to change the body without setting the proper option'
return
req = '%s%s' % (SMFIR_REPLBODY , body)
req = pack_uint32(len(req)) + req
self.send(req)
def addHeader(self , key , val):
"""
This will add a header to the email in the form:
key: val
NOTE: This can ONLY be called in eob()
"""
if not SMFIF_ADDHDRS & self._opts & self._mtaOpts:
print 'Add header called without the proper opts set'
return
req = '%s%s\0%s\0' % (SMFIR_ADDHEADER , key.rstrip(':') , val)
req = pack_uint32(len(req)) + req
self.send(req)
def chgHeader(self , key , val='' , index=1):
"""
This will change a header in the email. The "key" should be
exactly what was received in header(). If "val" is empty (''),
the header will be removed. "index" refers to which header to
remove in the case that there are multiple headers with the
same "key" (Received: is one example)
NOTE: This can ONLY be called in eob()
"""