File: CWSMTP.m

package info (click to toggle)
pantomime 1.3.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 2,332 kB
  • sloc: objc: 22,026; makefile: 11; sh: 4
file content (1154 lines) | stat: -rw-r--r-- 26,704 bytes parent folder | download
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
/*
**  CWSMTP.m
**
**  Copyright (c) 2001-2007 Ludovic Marcotte
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**  
**  This library 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
**  Lesser General Public License for more details.
**  
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#import <Pantomime/CWSMTP.h>

#import <Pantomime/CWConnection.h>
#import <Pantomime/CWConstants.h>
#import <Pantomime/CWInternetAddress.h>
#import <Pantomime/CWMD5.h>
#import <Pantomime/CWMessage.h>
#import <Pantomime/CWTCPConnection.h>
#import <Pantomime/NSData+Extensions.h>

#import <Foundation/NSEnumerator.h>
#import <Foundation/NSNotification.h>

//
// Some static variables used to enhance the performance.
//
static NSStringEncoding defaultCStringEncoding;
static NSData *CRLF;


//
// This function returns the next recipient from the array depending
// if the message is redirected or not.
//
static inline CWInternetAddress *next_recipient(NSMutableArray *theRecipients, BOOL aBOOL)
{
  CWInternetAddress *theAddress;
  NSUInteger i, count;

  count = [theRecipients count];

  for (i = 0; i < count; i++)
    {
      theAddress = [theRecipients objectAtIndex: i];

      if (aBOOL)
	{
	  if ([theAddress type] > 3)
	    {
	      return theAddress;
	    }
	}
      else
	{
	  if ([theAddress type] < 4)
	    {
	      return theAddress;
	    }
	}
    }

  return nil;
}

//
//
//
@interface CWSMTPQueueObject : NSObject
{
  @public
    SMTPCommand command;
    NSString *arguments;
}
- (id) initWithCommand: (SMTPCommand) theCommand
	     arguments: (NSString *) theArguments;
@end

@implementation CWSMTPQueueObject

- (id) initWithCommand: (SMTPCommand) theCommand
	     arguments: (NSString *) theArguments
{
  self = [super init];
  if (self)
    {
      command = theCommand;
      ASSIGN(arguments, theArguments);
    }
  
  return self;
}

- (void) dealloc
{
  RELEASE(arguments);
  [super dealloc];
}
@end


//
// Private SMTP methods
//
@interface CWSMTP (Private)

- (void) _fail;
- (void) _parseAUTH_CRAM_MD5;
- (void) _parseAUTH_LOGIN;
- (void) _parseAUTH_LOGIN_CHALLENGE;
- (void) _parseAUTH_PLAIN;
- (void) _parseAUTHORIZATION;
- (void) _parseDATA;
- (void) _parseEHLO;
- (void) _parseHELO;
- (void) _parseMAIL;
- (void) _parseNOOP;
- (void) _parseQUIT;
- (void) _parseRCPT;
- (void) _parseRSET;
- (void) _parseServerOutput;

@end


//
//
//
@implementation CWSMTP

+ (void) initialize
{
  defaultCStringEncoding = [NSString defaultCStringEncoding];
  CRLF = [[NSData alloc] initWithBytes: "\r\n"  length: 2];
}


//
// initializers
//
- (id) initWithName: (NSString *) theName
	       port: (unsigned int) thePort
{
  self = [super initWithName: theName  port: thePort];
  if (self)
    {
      _sent_recipients = nil;
      _recipients = nil;
      _message = nil;
      _data = nil;
      _max_size = 0;

      _lastCommand = SMTP_AUTHORIZATION;
  
      // We queue our first "command".
      [_queue addObject: AUTORELEASE([[CWSMTPQueueObject alloc] initWithCommand: _lastCommand  arguments: @""])];
    }
  
  return self;
}


//
//
//
- (void) dealloc
{
  //NSLog(@"SMTP: -dealloc");
  RELEASE(_message);
  RELEASE(_data);
  RELEASE(_recipients);
  RELEASE(_sent_recipients);

  [super dealloc];
}


//
// This method returns the last response obtained from the SMTP
// server. If the last command issued a multiline response, it'll return the
// last text response and none of the previous ones.
//
- (NSData *) lastResponse
{
  return [_responsesFromServer lastObject];
}


//
// Same as -lastResponse except it does return only the response code.
//
- (int) lastResponseCode
{
  if ([_responsesFromServer count] > 0)
    {
      return atoi([[[_responsesFromServer lastObject] subdataToIndex: 3] cString]);
    }

  return 0;
}


//
// This method is used to authenticate ourself to the SMTP server.
//
- (void) authenticate: (NSString *) theUsername
	     password: (NSString *) thePassword
	    mechanism: (NSString *) theMechanism
{
  ASSIGN(_username, theUsername);
  ASSIGN(_password, thePassword);
  ASSIGN(_mechanism, theMechanism);

  if (!theMechanism)
    {
      AUTHENTICATION_FAILED(_delegate, @"");
    }
  else if ([theMechanism caseInsensitiveCompare: @"PLAIN"] == NSOrderedSame)
    {
      [self sendCommand: SMTP_AUTH_PLAIN  arguments: @"AUTH PLAIN"];
    }
  else if ([theMechanism caseInsensitiveCompare: @"LOGIN"] == NSOrderedSame)
    {
      [self sendCommand: SMTP_AUTH_LOGIN  arguments: @"AUTH LOGIN"];
    }
  else if ([theMechanism caseInsensitiveCompare: @"CRAM-MD5"] == NSOrderedSame)
    {
      [self sendCommand: SMTP_AUTH_CRAM_MD5  arguments: @"AUTH CRAM-MD5"];
    }
  else
    {
      // Unknown / Unsupported mechanism
      AUTHENTICATION_FAILED(_delegate, theMechanism);
    }
}


//
//
//
- (void) close
{
  [self sendCommand: SMTP_QUIT  arguments: @"QUIT"];
}


//
// This method sends a NOOP SMTP command.
//
- (void) noop
{
  [self sendCommand: SMTP_NOOP  arguments: @"NOOP"];
}


//
// This method sends a RSET SMTP command.
//
- (void) reset
{ 
  [self sendCommand: SMTP_RSET  arguments: @"RSET"];
}


//
// This method sends a SMTP command to the server.
//
// It automatically adds the trailing CRLF to every command.
//
// RFC2821:
//
//   The SMTP commands define the mail transfer or the mail system
//   function requested by the user.  SMTP commands are character strings
//   terminated by <CRLF>.  The commands themselves are alphabetic
//   characters terminated by <SP> if parameters follow and <CRLF>
//   otherwise.  (In the interest of improved interoperability, SMTP
//   receivers are encouraged to tolerate trailing white space before the
//   terminating <CRLF>.)  The syntax of the local part of a mailbox must
//   conform to receiver site conventions and the syntax specified in
//   section 4.1.2.  The SMTP commands are discussed below.  The SMTP
//   replies are discussed in section 4.2.
//
// The following list of commands is supported:
//
// - EHLO / HELO
// - MAIL 
// - RCPT
// - DATA
// - RSET
// - QUIT
//
// Unimplemented commands:
//
// - VRFY
// - EXPN
// - HELP
// - NOOP
//
- (void) sendCommand: (SMTPCommand) theCommand  arguments: (NSString *) theFormat, ...
{
  CWSMTPQueueObject *aQueueObject;

  if (theCommand == SMTP_EMPTY_QUEUE)
    {
      if ([_queue count])
	{
	  // We dequeue the first inserted command from the queue.
	  aQueueObject = [_queue lastObject];
	}
      else
	{
	  // The queue is empty, we have nothing more to do...
	  return;
	}
    }
  else
    {
      NSString *aString;
      va_list args;
      
      va_start(args, theFormat);
      
      aString = [[NSString alloc] initWithFormat: theFormat  arguments: args];
      
      aQueueObject = [[CWSMTPQueueObject alloc] initWithCommand: theCommand  arguments: aString];
      RELEASE(aString);

      [_queue insertObject: aQueueObject  atIndex: 0];
      RELEASE(aQueueObject);

      // If we had queued commands, we return since we'll eventually
      // dequeue them one by one. Otherwise, we run it immediately.
      if ([_queue count] > 1)
	{
	  return;
	}
    }
  
  _lastCommand = aQueueObject->command;

  // We send the command to the POP3 server.
  [self writeData: [aQueueObject->arguments dataUsingEncoding: defaultCStringEncoding]];
  [self writeData: CRLF];
}


//
// To send a message, we need its data value and the recipients at least.
//
// Depending on what was specified using the "set" methods, we initialize
// what we really want and proceed to send the mail.
//
- (void) sendMessage
{
  NSString *aString;

  if (!_message && !_data)
    {
      [self _fail];
      return;
    }
  if (!_recipients && _message)
    {
      ASSIGN(_recipients, [NSMutableArray arrayWithArray: [_message recipients]]);

      if (!_data)
	{
	  ASSIGN(_data, [_message dataValue]);
	}
    }
  else if (!_recipients && _data)
    {
      CWMessage *aMessage;
      
      aMessage = [[CWMessage alloc] initWithData: _data];
      ASSIGN(_message, aMessage);
      ASSIGN(_recipients, [NSMutableArray arrayWithArray: [aMessage recipients]]);

      RELEASE(aMessage);
    }

  DESTROY(_sent_recipients);
  _sent_recipients = [_recipients mutableCopy];
  
  // We first verify if it's a redirected message
  if ([_message resentFrom])
    {
      _redirected = YES;
      aString = [[_message resentFrom] address];
    }
  else
    {
      _redirected = NO;
      aString = [[_message from] address];
    }

  if (_max_size)
    {
      [self sendCommand: SMTP_MAIL  arguments: @"MAIL FROM:<%@> SIZE=%d", aString, [_data length]];
    }
  else
    {
      [self sendCommand: SMTP_MAIL  arguments: @"MAIL FROM:<%@>", aString];
    }
}


//
//
//
- (void) setMessage: (CWMessage *) theMessage
{
  DESTROY(_data);
  ASSIGN(_message, theMessage);
}

- (CWMessage *) message
{
  return _message;
}


//
//
//
- (void) setMessageData: (NSData *) theData
{
  DESTROY(_message);
  ASSIGN(_data, theData);
}

- (NSData *) messageData
{
  return _data;
}


//
//
//
- (void) setRecipients: (NSArray *) theRecipients
{
  DESTROY(_recipients);

  if (theRecipients)
    {
      ASSIGN(_recipients, [NSMutableArray arrayWithArray: theRecipients]);
    }
}

- (NSArray *) recipients
{
  return _recipients;
}


//
// This methods reads everything the server sends. Once it judge it has
// read a full response, it calls _parseServerOutput in order to react
// to what we've just received from the server.
// 
//
// RFC2821 rationale:
//
//   An SMTP reply consists of a three digit number (transmitted as three
//   numeric characters) followed by some text unless specified otherwise
//   in this document.  The number is for use by automata to determine
//   what state to enter next; the text is for the human user.  The three
//   digits contain enough encoded information that the SMTP client need
//   not examine the text and may either discard it or pass it on to the
//   user, as appropriate.  Exceptions are as noted elsewhere in this
//   document.  In particular, the 220, 221, 251, 421, and 551 reply codes
//   are associated with message text that must be parsed and interpreted
//   by machines
//
//   (...)
//
//   The format for multiline replies requires that every line, except the
//   last, begin with the reply code, followed immediately by a hyphen,
//   "-" (also known as minus), followed by text.  The last line will
//   begin with the reply code, followed immediately by <SP>, optionally
//   some text, and <CRLF>.  As noted above, servers SHOULD send the <SP>
//   if subsequent text is not sent, but clients MUST be prepared for it
//   to be omitted.
//
//   For example:
//
//      123-First line
//      123-Second line
//      123-234 text beginning with numbers
//      123 The last line
//
//
//  (...)
//
//   ... Only the EHLO, EXPN, and HELP
//   commands are expected to result in multiline replies in normal
//   circumstances, however, multiline replies are allowed for any
//   command.
//
- (void) updateRead
{
  NSData *aData;
  char *buf;
  int count;

  //NSLog(@"IN UPDATE READ");

  [super updateRead];

  while ((aData = split_lines(_rbuf)))
    {
      [_responsesFromServer addObject: aData];
 
      buf = (char *)[aData bytes];
      count = [aData length];

      // If we got only a response code OR if we're done reading
      // a multiline reply, we parse the output!
      if (count == 3 || (count > 3 && (*(buf+3) != '-')))
	{
	  [self _parseServerOutput];
	}
    }
}

//
//
//
- (void) startTLS
{
  [self sendCommand: SMTP_STARTTLS  arguments: @"STARTTLS"];
}

@end


//
// Private methods
//
@implementation CWSMTP (Private)
- (void) _fail
{
  if (_message)
    POST_NOTIFICATION(PantomimeMessageNotSent, self,
                [NSDictionary dictionaryWithObject: _message  forKey: @"Message"]);
  else
    POST_NOTIFICATION(PantomimeMessageNotSent, self,
                [NSDictionary dictionaryWithObject: AUTORELEASE([CWMessage new])  forKey: @"Message"]);
  PERFORM_SELECTOR_2(_delegate, @selector(messageNotSent:), PantomimeMessageNotSent, _message, @"Message");
}

- (void) _parseAUTH_CRAM_MD5
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
 
  if ([aData hasCPrefix: "334"])
    {
      NSString *aString;
      CWMD5 *aMD5;
      
      // We trim the "334 ", decode the data using base64 and we keep the challenge phrase
      aData = [[aData subdataFromIndex: 4] decodeBase64];
      aMD5 = [[CWMD5 alloc] initWithData: aData];
      [aMD5 computeDigest];
      
      aString = [NSString stringWithFormat: @"%@ %@", _username, [aMD5 hmacAsStringUsingPassword: _password]];
      [self writeData: [[aString dataUsingEncoding: defaultCStringEncoding] encodeBase64WithLineLength: 0]];
      [self writeData: CRLF];
      RELEASE(aMD5);
    }
  else if ([aData hasCPrefix: "235"])
    {
      AUTHENTICATION_COMPLETED(_delegate, @"CRAM-MD5");
    }
  else
    {
      AUTHENTICATION_FAILED(_delegate, @"CRAM-MD5");
    }
}


//
//
//
- (void) _parseAUTH_LOGIN
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "334"])
    {
      NSString *aString;
      
      aString = [[NSString alloc] initWithData: [[_username dataUsingEncoding: defaultCStringEncoding] encodeBase64WithLineLength: 0]
						   encoding: defaultCStringEncoding];
      [self sendCommand: SMTP_AUTH_LOGIN_CHALLENGE  arguments: aString];
      RELEASE(aString);
    }
  else
    {
      AUTHENTICATION_FAILED(_delegate, @"LOGIN");
    }
}


//
// FIXME, rename if needed.
//
- (void) _parseAUTH_LOGIN_CHALLENGE
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "334"])
    {
      NSString *aString;
      
      aString = [[NSString alloc] initWithData: [[_password dataUsingEncoding: defaultCStringEncoding] encodeBase64WithLineLength: 0]
				  encoding: defaultCStringEncoding];
      
      [self sendCommand: SMTP_AUTH_LOGIN_CHALLENGE  arguments: aString];
      RELEASE(aString);
    }
  else if ([aData hasCPrefix: "235"])
    {
      AUTHENTICATION_COMPLETED(_delegate, @"LOGIN");
    }
  else
    {
      AUTHENTICATION_FAILED(_delegate, @"LOGIN");
    }
}


//
//
//
- (void) _parseAUTH_PLAIN
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];

  if ([aData hasCPrefix: "334"])
    {
      NSMutableData *aMutableData;
      int len_username, len_password;
      
      len_username = [_username length];
  
      if (!_password)
	{
	  len_password = 0;
	}
      else
	{
	  len_password = [_password length];
	}
      
      // We create our phrase
      aMutableData = [NSMutableData dataWithLength: (len_username + len_password + 2)];
      
      [aMutableData replaceBytesInRange: NSMakeRange(1,len_username)
		    withBytes: [[_username dataUsingEncoding: defaultCStringEncoding] bytes]];
      
      
      [aMutableData replaceBytesInRange: NSMakeRange(2 + len_username, len_password)
		    withBytes: [[_password dataUsingEncoding: defaultCStringEncoding] bytes]];
      
      [self writeData: [aMutableData encodeBase64WithLineLength: 0]];
      [self writeData: CRLF];
    }
  else if ([aData hasCPrefix: "235"])
    {
      AUTHENTICATION_COMPLETED(_delegate, @"PLAIN");
    }
  else
    {
      AUTHENTICATION_FAILED(_delegate, @"PLAIN");
    }
}

//
//
//
- (void) _parseAUTHORIZATION
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  // 220 <domain> Service ready
  if ([aData hasCPrefix: "220"])
    {
      [self sendCommand: SMTP_EHLO  arguments: @"EHLO localhost.localdomain"];
    }
  else
    {
      // Handle the fact when a server is loaded and can't handle our requests
      // right away.
#warning FIXME
    }
}

//
//
//
- (void) _parseDATA
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];

  // If we can proceed to write the message's data, let's do so.
  if ([aData hasCPrefix: "354"])
    {
      NSMutableData *aMutableData;
      NSRange r1, r2;
      
      // We first replace all occurences of LF by CRLF in the Message's data.
      //
      aMutableData = [[NSMutableData dataWithData: _data] replaceLFWithCRLF];
  
      //
      // According to RFC 2821 section 4.5.2, we must check for the character
      // sequence "<CRLF>.<CRLF>"; any occurrence have its period duplicated
      // to avoid data transparency. 
      //
      r1 = [aMutableData rangeOfCString: "\r\n."];
      
      while (r1.location != NSNotFound)
	{
	  [aMutableData replaceBytesInRange: r1  withBytes: "\r\n.."  length: 4];
	  
	  r1 = [aMutableData rangeOfCString: "\r\n."
			     options: 0 
			     range: NSMakeRange(NSMaxRange(r1)+1, [aMutableData length]-NSMaxRange(r1)-1)];
	}

      //
      // We now look for the Bcc: header. If it is present, we remove it.
      // Some servers, like qmail, do not remove it automatically.
      //
      r1 = [aMutableData rangeOfCString: "\r\n\r\n"];
      r1 = [aMutableData rangeOfCString: "\r\nBcc: "
			 options: 0
			 range: NSMakeRange(0,r1.location-1)];
      
      if (r1.location != NSNotFound)
	{
	  // We search for the first \r\n AFTER the Bcc: header and
	  // replace the whole thing with \r\n.
	  r2 = [aMutableData rangeOfCString: "\r\n"
			     options: 0
			     range: NSMakeRange(NSMaxRange(r1)+1,[aMutableData length]-NSMaxRange(r1)-1)];
	  [aMutableData replaceBytesInRange: NSMakeRange(r1.location, NSMaxRange(r2)-r1.location)
			withBytes: "\r\n"
			length: 2];
	}
 
      [self writeData: aMutableData];
      [self writeData: [NSData dataWithBytes: "\r\n.\r\n"  length: 5]];
    }
  else if ([aData hasCPrefix: "250"])
    {
      // The data we wrote in the previous call was sucessfully written.
      // We inform the delegate that the mail was sucessfully sent.
      POST_NOTIFICATION(PantomimeMessageSent, self, [NSDictionary dictionaryWithObject: _message  forKey: @"Message"]);
      PERFORM_SELECTOR_2(_delegate, @selector(messageSent:), PantomimeMessageSent, _message, @"Message");
    }
  else
    {
      [self _fail];
    }
}


//
//
//
- (void) _parseEHLO
{
  NSData *aData;
  int i, count;

  count = [_responsesFromServer count];
  
  for (i = 0; i < count; i++)
    {
      aData = [_responsesFromServer objectAtIndex: i];

      if ([aData hasCPrefix: "250"])
	{
	  // We parse the SMTP service extensions. For now, we support the SIZE
	  // and the AUTH extensions. We ignore the rest.
	  aData = [aData subdataFromIndex: 4];

	  // We add it to our capabilities
	  [_capabilities addObject: AUTORELEASE([[NSString alloc] initWithData: aData  encoding: defaultCStringEncoding])];

	  // Example of responses:
	  //
	  // AUTH LOGIN
	  // AUTH=PLAIN CRAM-MD5 DIGEST-MD5
	  //
	  if ([aData hasCPrefix: "AUTH"])
	    {
	      NSEnumerator *theEnumerator;
	      id aString;

	      // We chomp the "AUTH " or "AUTH=" part and we decode our
	      // supported mechanisms.
	      theEnumerator = [[[aData subdataFromIndex: 5] componentsSeparatedByCString: " "] objectEnumerator];

	      while ((aString = [theEnumerator nextObject]))
		{
		  aString = [aString asciiString];

		  if (![_supportedMechanisms containsObject: aString])
		    {
		      [_supportedMechanisms addObject: aString];
		    }
		}
	    }
	  //
	  // SIZE size-param
	  // size-param ::= [1*DIGIT]
	  //
	  // See RFC1870 for detailed information.
	  //
	  else if ([aData hasCPrefix: "SIZE"])
	    {
	      NSRange aRange;

	      // We must be careful here. Some broken servers will send only
	      // 250-SIZE
	      // and we don't want to parse an inexistant value.
	      aRange = [aData rangeOfCString: " "];

	      if (aRange.length)
		{
		  _max_size = atoi([[aData subdataFromIndex: aRange.location+1] cString]);
		}
	    }
	}
      else
	{
	  // The server doesn't handle EHLO. We send it
	  // a HELO greeting instead.
	  [self sendCommand: SMTP_HELO  arguments: @"HELO localhost.localdomain"];
	  break;
	}
    }


#warning FIXME - Inform the delegate if it is ready or not, especially if EHLO failed
  POST_NOTIFICATION(PantomimeServiceInitialized, self, nil);
  PERFORM_SELECTOR_1(_delegate, @selector(serviceInitialized:), PantomimeServiceInitialized);
}


//
//
//
- (void) _parseHELO
{
  // FIXME - Implement. + inform the delegate if it's ready or not.
}


//
// This method parses the result received from the server
// after issuing a "MAIL FROM: <>" command.
//
// If the result is successful, we proceed by sending the first RCPT.
//
- (void) _parseMAIL
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];

  if ([aData hasCPrefix: "250"])
    {
      // We write the first recipient while respecting the fact
      // that we are bouncing or not the message.
      POST_NOTIFICATION(PantomimeTransactionInitiationCompleted, self, [NSDictionary dictionaryWithObject: _message  forKey: @"Message"]);
      PERFORM_SELECTOR_1(_delegate, @selector(transactionInitiationCompleted:), PantomimeTransactionInitiationCompleted);

      [self sendCommand: SMTP_RCPT  arguments: @"RCPT TO:<%@>", [next_recipient(_sent_recipients, _redirected) address]];
    }
  else
    {
      if (PERFORM_SELECTOR_1(_delegate, @selector(transactionInitiationFailed:), PantomimeTransactionInitiationFailed))
	{
	  POST_NOTIFICATION(PantomimeTransactionInitiationFailed, self, [NSDictionary dictionaryWithObject: _message  forKey: @"Message"]);
	}
      else
	{
	  [self _fail];
	}
    }
}


//
//
//
- (void) _parseNOOP
{
  // Do what?
}


//
//
//
- (void) _parseQUIT
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "221"])
    {
      // Do anything special here?
    }

  [super close];
}


//
// This method is invoked everytime we sent a recipient to the
// server using the RCPT command.
//
// If it was successful, this command sends the next one, if any
// by first removing the previously sent one from _recipients.
//
- (void) _parseRCPT
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];

  if ([aData hasCPrefix: "250"])
    {
      CWInternetAddress *theAddress;

      theAddress = next_recipient(_sent_recipients, _redirected);

      if (theAddress)
	{
	  [_sent_recipients removeObject: theAddress];
	  
	  theAddress = next_recipient(_sent_recipients, _redirected);
	  
	  if (theAddress)
	    {
	      [self sendCommand: SMTP_RCPT  arguments: @"RCPT TO:<%@>", [theAddress address]];
	      return;
	    }
	}

      // We are done writing the recipients, we now write the content
      // of the message.
      POST_NOTIFICATION(PantomimeRecipientIdentificationCompleted, self, [NSDictionary dictionaryWithObject: _recipients  forKey: @"Recipients"]);
      PERFORM_SELECTOR_2(_delegate, @selector(recipientIdentificationCompleted:), PantomimeRecipientIdentificationCompleted, _recipients, @"Recipients");
      [self sendCommand: SMTP_DATA  arguments: @"DATA"];
    }
  else
    {
#warning also send the invalid recipient in perform selector and when posting the notification
      if (PERFORM_SELECTOR_1(_delegate, @selector(recipientIdentificationFailed:), PantomimeRecipientIdentificationFailed))
	{
	  POST_NOTIFICATION(PantomimeRecipientIdentificationFailed, self, [NSDictionary dictionaryWithObject: _recipients  forKey: @"Recipients"]);
	}
      else
	{
	  [self _fail];
	}
    }
}

//
//
//
- (void) _parseRSET
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "250"])
    {
      POST_NOTIFICATION(PantomimeTransactionResetCompleted, self, nil);
      PERFORM_SELECTOR_1(_delegate, @selector(transactionResetCompleted:), PantomimeTransactionResetCompleted);
    }
  else
    {
      POST_NOTIFICATION(PantomimeTransactionResetFailed, self, nil);
      PERFORM_SELECTOR_1(_delegate, @selector(transactionResetFailed:), PantomimeTransactionResetFailed);
    }
}

//
//
//
- (void) _parseSTARTTLS
{
  NSData *aData;

  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "220"])
    {          
      // We first activate SSL.
      [(CWTCPConnection *)_connection startSSL];

      // We now forget about the initial negotiated state; see RFC2487 for more details,
      [_supportedMechanisms removeAllObjects];
      [self sendCommand: SMTP_EHLO  arguments: @"EHLO localhost.localdomain"];
    }
  else
    {
      // The server probably doesn't support TLS. We inform the delegate that the transaction initiation
      // failed or that the message wasn't sent.
      if (PERFORM_SELECTOR_1(_delegate, @selector(transactionInitiationFailed:), PantomimeTransactionInitiationFailed))
	{
	  POST_NOTIFICATION(PantomimeTransactionInitiationFailed, self, [NSDictionary dictionaryWithObject: _message  forKey: @"Message"]);
	}
      else
	{
	  [self _fail];
	}
    }
}

//
//
//
- (void) _parseServerOutput
{
  NSData *aData;

  if (![_responsesFromServer count])
    {
      return;
    }

  // We read only the first response. The _parseXYZ methods
  // will handle multiline responses.
  aData = [_responsesFromServer objectAtIndex: 0];

  if ([aData hasCPrefix: "421"])
    {
      // FIXME: - lost connection
      //NSLog(@"LOST CONNECTION TO THE SERVER");
      [super close];
    }
  else
    {
      switch (_lastCommand)
	{
	case SMTP_AUTH_CRAM_MD5:
	  [self _parseAUTH_CRAM_MD5];
	  break;

	case SMTP_AUTH_LOGIN:
	  [self _parseAUTH_LOGIN];
	  break;
	  
	case SMTP_AUTH_LOGIN_CHALLENGE:
	  [self _parseAUTH_LOGIN_CHALLENGE];
	  break;

	case SMTP_AUTH_PLAIN:
	  [self _parseAUTH_PLAIN];
	  break;

	case SMTP_DATA:
	  [self _parseDATA];
	  break;

	case SMTP_EHLO:
	  [self _parseEHLO];
	  break;
	  
	case SMTP_HELO:
	  [self _parseHELO];
	  break;

	case SMTP_MAIL:
	  [self _parseMAIL];
	  break;

	case SMTP_NOOP:
	  [self _parseNOOP];
	  break;

	case SMTP_QUIT:
	  [self _parseQUIT];
	  break;

	case SMTP_RCPT:
	  [self _parseRCPT];
	  break;

	case SMTP_RSET:
	  [self _parseRSET];
	  break;

	case SMTP_STARTTLS:
	  [self _parseSTARTTLS];
	  break;
	  
	case SMTP_AUTHORIZATION:
	  [self _parseAUTHORIZATION];
	  break;

	default:
	  break;
	  // FIXME
	}
    }
  
  // We are done parsing this entry...
  [_responsesFromServer removeAllObjects];

  // We remove the last object of the queue....
  if ([_queue lastObject])
    {
      [_queue removeLastObject];
    }

  [self sendCommand: SMTP_EMPTY_QUEUE  arguments: @""];
}

@end